Compare commits
93 Commits
v0.1.0
...
v0.3.0-bet
Author | SHA1 | Date | |
---|---|---|---|
|
b46d047411 | ||
|
542c549e4e | ||
|
ebb9a6daa0 | ||
|
f93a94ddf1 | ||
|
597fc95cef | ||
|
df81dda22d | ||
|
5836965a1e | ||
|
58d80b8eb3 | ||
|
a4b4a3f24c | ||
|
ace6019197 | ||
|
88cefeabbf | ||
|
bf2afd8739 | ||
|
0b087ee08c | ||
|
c1746697b9 | ||
|
5179c4dbb5 | ||
|
64973f57cf | ||
|
00a00be692 | ||
|
9e8dade238 | ||
|
9babad6b33 | ||
|
00896ab280 | ||
|
f03cd76f52 | ||
|
0453c1db30 | ||
|
013be139c9 | ||
|
317fc367f8 | ||
|
efc54e73f2 | ||
|
0182ec7251 | ||
|
640ccb7ef8 | ||
|
2e694349c9 | ||
|
9328fa1eb4 | ||
|
221d823f3b | ||
|
8b6eadb9ab | ||
|
22d8380bce | ||
|
0cbf1a83a5 | ||
|
23f717579e | ||
|
4eb8c95c3a | ||
|
0fa04e4a54 | ||
|
f97aa8cbef | ||
|
37b0f29184 | ||
|
2befdbb54f | ||
|
d1a6c84e6b | ||
|
e8229b867a | ||
|
6fb18d5827 | ||
|
a8488a0745 | ||
|
89a7416367 | ||
|
068c6b8555 | ||
|
9a90d846e6 | ||
|
16efe93920 | ||
|
8fbb45037c | ||
|
f1196d5b72 | ||
|
3b4736b00f | ||
|
5796982f2d | ||
|
9e6d3ab5dd | ||
|
571506d1d2 | ||
|
c00adcf575 | ||
|
808aed2bc3 | ||
|
ec0a9c7b80 | ||
|
84afb86b77 | ||
|
02c5523d6d | ||
|
d7cf31fb9a | ||
|
d7258cd3c6 | ||
|
222f7f104a | ||
|
548dace78c | ||
|
001de470ca | ||
|
09b789dfc2 | ||
|
55b759a31c | ||
|
cb0ffe0575 | ||
|
3cde0b9c23 | ||
|
2ce3bab3b6 | ||
|
ba723f8523 | ||
|
d2d5f80b44 | ||
|
e2a097b2d0 | ||
|
45a81e5979 | ||
|
158060a3b0 | ||
|
1e3b832186 | ||
|
8294990b1f | ||
|
a704ba2e6c | ||
|
a7303fef15 | ||
|
cd6960fa80 | ||
|
c05ca68de4 | ||
|
a8df386d58 | ||
|
4b0d549dd6 | ||
|
85236793e1 | ||
|
954dcf3a5c | ||
|
466a3d270e | ||
|
a046f9f327 | ||
|
c03573b24f | ||
|
694e62edee | ||
|
61399c7705 | ||
|
05d1594ac2 | ||
|
361596e773 | ||
|
d57aef36ea | ||
|
0033d0dc1d | ||
|
1c43ca7666 |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -7,4 +7,7 @@ out/
|
||||
.idea/
|
||||
|
||||
# Local dev config
|
||||
application.yaml
|
||||
/application.yaml
|
||||
|
||||
# Local dev storage
|
||||
/mxisd.db
|
||||
|
144
README.md
144
README.md
@@ -1,23 +1,34 @@
|
||||
mxisd
|
||||
mxisd - Federated Matrix Identity Server Daemon
|
||||
-----
|
||||

|
||||
|
||||
[Overview](#overview) | [Lookup process](#lookup-process) | [Packages](#packages) | [From source](#from-source) | [Network Discovery](#network-discovery) | [Integration](#integration) | [Support](#support)
|
||||
[Overview](#overview) | [Features](#features) | [Lookup process](#lookup-process) | [Packages](#packages) |
|
||||
[From source](#from-source) | [Configuration](#configuration) | [Network Discovery](#network-discovery) |
|
||||
[Integration](#integration) | [Support](#support)
|
||||
|
||||
# Overview
|
||||
mxisd is an implementation of the [Matrix Identity Service specification](https://matrix.org/docs/spec/identity_service/unstable.html)
|
||||
which provides an alternative to the vector.im and matrix.org Identity servers.
|
||||
mxisd is a Federated Matrix Identity server for self-hosted Matrix infrastructures.
|
||||
|
||||
mxisd is federated and uses a cascading lookup model which performs lookup from a more authoritative to a less authoritative source, usually doing:
|
||||
mxisd uses a cascading lookup model which performs lookup from a more authoritative to a less authoritative source, usually doing:
|
||||
- Local identity stores: LDAP, etc.
|
||||
- Federated identity stores: another Identity Server in charge of a specific domain, if applicable
|
||||
- Configured identity stores: another Identiy Server specifically configured, if part of some sort of group trust
|
||||
- Root identity store: vector.im/matrix.org central Identity Server
|
||||
- Configured identity stores: another Identity Server specifically configured, if part of some sort of group trust
|
||||
- Root identity store: vector.im/matrix.org central Identity Servers
|
||||
|
||||
mxisd only aims to support workflow that does NOT break federation or basic lookup process of the Matrix ecosystem.
|
||||
mxisd provides an alternative to [sydent](https://github.com/matrix-org/sydent), while still connecting to the vector.im and matrix.org Identity servers,
|
||||
by implementing the [Matrix Identity Service specification](https://matrix.org/docs/spec/identity_service/unstable.html).
|
||||
|
||||
**NOTE:** mxisd is **NOT** an authenticator module for homeservers. Identity servers are opaque public directories for those who publish their data on it.
|
||||
For more details, please read the [Identity Service specification](https://matrix.org/docs/spec/identity_service/unstable.html).
|
||||
mxisd only aims to support workflows that do NOT break federation or basic lookup processes of the Matrix ecosystem.
|
||||
|
||||
# Features
|
||||
- Single lookup of 3PID (E-mail, phone number, etc.) by the Matrix Client or Homeserver.
|
||||
- Bulk lookups when trying to find possible matches within contacts in Android and iOS clients.
|
||||
- Bind of 3PID by a Matrix user within a Matrix client.
|
||||
- Support of invitation to rooms by e-mail with e-mail notification to invitee.
|
||||
- Authentication support in [synapse](https://github.com/matrix-org/synapse) via the [REST auth module](https://github.com/kamax-io/matrix-synapse-rest-auth).
|
||||
|
||||
In the pipe:
|
||||
- Support to proxy 3PID bindings in user profile to the central Matrix.org servers
|
||||
|
||||
# Lookup Process
|
||||
Default Lookup strategy will use a priority order and a configurable recursive/local type of request.
|
||||
@@ -39,21 +50,16 @@ Given the phone number `+123456789`, the following lookup logic will be performe
|
||||
See [releases]((https://github.com/kamax-io/mxisd/releases)) for native installers of supported systems.
|
||||
If none is available, please use other packages or build from source.
|
||||
|
||||
## Docker
|
||||
### From source
|
||||
Build the image:
|
||||
```
|
||||
docker build -t your-org/mxisd:$(git describe --tags --always --dirty) .
|
||||
```
|
||||
You can run a container of the given image and test it with the following command (adapt volumes host paths):
|
||||
```
|
||||
docker run -v /data/mxisd/etc:/etc/mxisd -v /data/mxisd/var:/var/mxisd -p 8090:8090 -t your-org/mxisd:$(git describe --tags --always --dirty)
|
||||
```
|
||||
|
||||
## Debian
|
||||
### Download
|
||||
See the [releases section](https://github.com/kamax-io/mxisd/releases).
|
||||
|
||||
### Configure and run
|
||||
After installation:
|
||||
1. Copy the sample config file `/etc/mxisd/mxisd-sample.yaml` to `/etc/mxisd/mxisd.yaml`
|
||||
2. [Configure](#configuration)
|
||||
3. Start the service: `sudo systemctl start mxisd`
|
||||
|
||||
### From source
|
||||
Requirements:
|
||||
- fakeroot
|
||||
@@ -63,9 +69,24 @@ Run:
|
||||
```
|
||||
./gradlew buildDeb
|
||||
```
|
||||
|
||||
You will find the debian package in `build/dist`
|
||||
|
||||
## Docker
|
||||
```
|
||||
docker pull kamax/mxisd
|
||||
```
|
||||
|
||||
For more info, see [the public repository](https://hub.docker.com/r/kamax/mxisd/)
|
||||
### From source
|
||||
[Build mxisd](#build) then build the docker image:
|
||||
```
|
||||
./gradlew dockerBuild
|
||||
```
|
||||
You can run a container of the given image and test it with the following command (adapt volumes host paths):
|
||||
```
|
||||
docker run -v /data/mxisd/etc:/etc/mxisd -v /data/mxisd/var:/var/mxisd -p 8090:8090 -t kamax/mxisd:latest-dev
|
||||
```
|
||||
|
||||
# From Source
|
||||
## Requirements
|
||||
- JDK 1.8
|
||||
@@ -76,15 +97,9 @@ git clone https://github.com/kamax-io/mxisd.git
|
||||
cd mxisd
|
||||
./gradlew build
|
||||
```
|
||||
then see the [Configuration](#configuration) section.
|
||||
|
||||
## Configure
|
||||
1. Create a new local config: `cp application.example.yaml application.yaml`
|
||||
2. Set the `server.name` value to the domain value used in your Home Server configuration
|
||||
3. Set an absolute location for the signing keys using `key.path`
|
||||
4. Provide the LDAP attributes you want to use for lookup, if you want to use one
|
||||
5. Edit an entity in your LDAP database and set the configure attribute with a Matrix ID (e.g. `@john.doe:example.org`)
|
||||
|
||||
## Test build and configuration
|
||||
## Test build
|
||||
Start the server in foreground to validate the build:
|
||||
```
|
||||
java -jar build/libs/mxisd.jar
|
||||
@@ -92,10 +107,18 @@ java -jar build/libs/mxisd.jar
|
||||
|
||||
Ensure the signing key is available:
|
||||
```
|
||||
curl http://localhost:8090/_matrix/identity/api/v1/pubkey/ed25519:0
|
||||
$ curl http://localhost:8090/_matrix/identity/api/v1/pubkey/ed25519:0
|
||||
{"public_key":"..."}
|
||||
```
|
||||
|
||||
Validate your LDAP config and binding info (replace the e-mail):
|
||||
Test basic recursive lookup (requires Internet connection with access to TCP 443):
|
||||
```
|
||||
$ curl 'http://localhost:8090/_matrix/identity/api/v1/lookup?medium=email&address=mxisd-lookup-test@kamax.io'
|
||||
{"address":"mxisd-lookup-test@kamax.io","medium":"email","mxid":"@mxisd-lookup-test:kamax.io",...}
|
||||
```
|
||||
|
||||
|
||||
If you enabled LDAP, you can also validate your config with a similar request after replacing the `address` value with something present within your LDAP
|
||||
```
|
||||
curl "http://localhost:8090/_matrix/identity/api/v1/lookup?medium=email&address=john.doe@example.org"
|
||||
```
|
||||
@@ -132,36 +155,71 @@ chmod a+x /opt/mxisd/mxisd.jar
|
||||
ln -s /opt/mxisd/mxisd.jar /usr/bin/mxisd
|
||||
```
|
||||
|
||||
2. Copy the config file created earlier `./application.yaml` to `/etc/mxisd/mxisd.yaml`
|
||||
3. Configure `/etc/mxisd/mxisd.yaml` with production value, `key.path` being the most important - `/var/opt/mxisd/signing.key` is recommended
|
||||
2. Copy the config file created earlier `./application.example.yaml` to `/etc/mxisd/mxisd.yaml`
|
||||
3. [Configure](#configuration)
|
||||
4. Copy `<repo root>/src/systemd/mxisd.service` to `/etc/systemd/system/` and edit if needed
|
||||
5. Manage service for auto-startup
|
||||
5. Enable service for auto-startup
|
||||
```
|
||||
# Enable service
|
||||
systemctl enable mxisd
|
||||
|
||||
# Start service
|
||||
```
|
||||
6. Start mxisd
|
||||
```
|
||||
systemctl start mxisd
|
||||
```
|
||||
|
||||
# Configuration
|
||||
After following the specific instructions to create a config file from the sample:
|
||||
1. Set the `matrix.domain` value to the domain value used in your Home Server configuration
|
||||
2. Set an absolute location for the signing keys using `key.path`
|
||||
3. Configure the E-mail invite sender with items starting in `invite.sender.email`
|
||||
|
||||
In case your IS public domain does not match your Matrix domain, see `server.name` and `server.publicUrl`
|
||||
config items.
|
||||
|
||||
|
||||
## Backends
|
||||
### LDAP (AD, Samba, LDAP)
|
||||
If you want to use LDAP backend as an Identity store:
|
||||
1. Enable it with `ldap.enabled`
|
||||
2. Configure connection options using items starting in `ldap.connection`
|
||||
3. You may want to valid default values for `ldap.attribute` items
|
||||
|
||||
### SQL (SQLite, PostgreSQL)
|
||||
If you want to connect to use a synapse DB (SQLite or PostgreSQL) as Identity store, follow the example config for `sql` config items.
|
||||
|
||||
### REST (Webapps/websites integration)
|
||||
If you want to use the REST backend as an Identity store:
|
||||
1. Enable it with `rest.enabled`
|
||||
2. Configure options starting with `rest` and see the dedicated documentation in `docs/backends/rest.md`
|
||||
|
||||
# Network Discovery
|
||||
To allow other federated Identity Server to reach yours, configure the following DNS SRV entry (adapt to your values):
|
||||
To allow other federated Identity Server to reach yours, the same algorithm used for Homeservers takes place:
|
||||
1. Check for the appropriate DNS SRV record
|
||||
2. If not found, use the base domain
|
||||
|
||||
If your Identity Server public hostname does not match your Matrix domain, configure the following DNS SRV entry
|
||||
and replace `matrix.example.com` by your Identity server public hostname - **Make sure to end with a final dot!**
|
||||
```
|
||||
_matrix-identity._tcp.example.com. 3600 IN SRV 10 0 443 matrix.example.com.
|
||||
```
|
||||
This would only apply for 3PID that are DNS-based, like e-mails. For anything else, like phone numbers, no federation is currently possible.
|
||||
This would only apply for 3PID that are DNS-based, like e-mails. For anything else, like phone numbers, no federation
|
||||
is currently possible.
|
||||
|
||||
The port must be HTTPS capable. Typically, the port `8090` of mxisd should be behind a reverse proxy which does HTTPS.
|
||||
See the [integration section](#integration) for more details.
|
||||
|
||||
# Integration
|
||||
- [HTTPS and Reverse proxy](https://github.com/kamax-io/mxisd/wiki/HTTPS)
|
||||
- [synapse](https://github.com/kamax-io/mxisd/wiki/Homeserver-Integration)
|
||||
- [synapse](https://github.com/kamax-io/mxisd/wiki/Homeserver-Integration) as Identity server
|
||||
- [synapse with REST auth module](https://github.com/kamax-io/matrix-synapse-rest-auth/blob/master/README.md)
|
||||
as authentication module
|
||||
|
||||
# Support
|
||||
## Community
|
||||
If you need help, want to report a bug or just say hi, you can reach us on Matrix at [#mxisd:kamax.io](https://matrix.to/#/#mxisd:kamax.io)
|
||||
For more high-level discussion about the Identity Server architecture/API, go to [#matrix-identity:matrix.org](https://matrix.to/#/#matrix-identity:matrix.org)
|
||||
If you need help, want to report a bug or just say hi, you can reach us on Matrix at
|
||||
[#mxisd:kamax.io](https://matrix.to/#/#mxisd:kamax.io) or [directly peek anonymously](https://view.matrix.org/room/!NPRUEisLjcaMtHIzDr:kamax.io/).
|
||||
For more high-level discussion about the Identity Server architecture/API, go to
|
||||
[#matrix-identity:matrix.org](https://matrix.to/#/#matrix-identity:matrix.org)
|
||||
|
||||
## Professional
|
||||
If you would prefer professional support/custom development for mxisd and/or for Matrix in general, including other open source technologies/products,
|
||||
|
@@ -1,148 +1,414 @@
|
||||
server:
|
||||
# Sample configuration file explaining all possible options, their default value and if they are required or not.
|
||||
#
|
||||
# Any optional configuration item will be prefixed by # (comment character) with the configuration item following
|
||||
# directly without any whitespace character.
|
||||
# Default values for optional configuration item will also follow such item.
|
||||
#
|
||||
# Any mandatory configuration item will not be prefixed by # and will also contain a value as example that must be
|
||||
# changed. It is advised to re-create a clean config file with only the required configuration item.
|
||||
|
||||
# Indicate on which port the Identity Server will listen.
|
||||
#
|
||||
# This is be default an unencrypted port.
|
||||
# HTTPS can be configured using Tomcat configuration properties.
|
||||
port: 8090
|
||||
|
||||
# Realm under which this Identity Server is authoritative, required.
|
||||
#
|
||||
# This is used to avoid unnecessary connections and endless recursive lookup.
|
||||
# e.g. domain name in e-mails.
|
||||
name: 'example.org'
|
||||
#######################
|
||||
# Matrix config items #
|
||||
#######################
|
||||
# Matrix domain, same as the domain configure in your Homeserver configuration.
|
||||
#
|
||||
# This is used to build the various identifiers for identity, auth and directory.
|
||||
matrix.domain: ''
|
||||
|
||||
|
||||
|
||||
key:
|
||||
#######################
|
||||
# Server config items #
|
||||
#######################
|
||||
# Indicate on which port the Identity Server will listen.
|
||||
#
|
||||
# This is be default an unencrypted port.
|
||||
# HTTPS can be configured using Tomcat configuration properties.
|
||||
#
|
||||
#server.port: 8090
|
||||
|
||||
# Absolute path for the Identity Server signing key, required.
|
||||
# During testing, /var/tmp/mxisd.key is a possible value
|
||||
#
|
||||
# For production, use a stable location like:
|
||||
# - /var/opt/mxisd/sign.key
|
||||
# - /var/local/mxisd/sign.key
|
||||
# - /var/lib/mxisd/sign.key
|
||||
path: '%SIGNING_KEYS_PATH%'
|
||||
|
||||
# Public hostname of this identity server.
|
||||
#
|
||||
# This would be typically be the same as your Matrix domain.
|
||||
# In case it is not, set this value.
|
||||
#
|
||||
# This value is used in various signatures within the Matrix protocol and should be a reachable hostname.
|
||||
# You can validate by ensuring you see a JSON answer when calling (replace the domain):
|
||||
# https://example.org/_matrix/identity/status
|
||||
#
|
||||
#server.name: 'example.org'
|
||||
|
||||
|
||||
# Public URL to reach this identity server
|
||||
#
|
||||
# This is used with 3PID invites in room and other Homeserver key verification workflow.
|
||||
# If left unconfigured, it will be generated from the server name.
|
||||
#
|
||||
# You should typically set this value if you want to change the public port under which
|
||||
# this Identity server is reachable.
|
||||
#
|
||||
# %SERVER_NAME% placeholder is available to avoid configuration duplication.
|
||||
# e.g. 'https://%SERVER_NAME%:8443'
|
||||
#
|
||||
#server.publicUrl: 'https://example.org'
|
||||
|
||||
|
||||
|
||||
# This element contains all the configuration item for lookup strategies
|
||||
lookup:
|
||||
|
||||
# Configuration items for recursion-type of lookup
|
||||
#
|
||||
# Lookup access are divided into two types:
|
||||
# - Local
|
||||
# - Remote
|
||||
#
|
||||
# This is similar to DNS lookup and recursion and is therefore prone to the same vulnerabilities.
|
||||
# By default, only non-public hosts are allowed to perform recursive lookup.
|
||||
#
|
||||
# This will also prevent very basic endless loops where host A ask host B, which in turn is configured to ask host A,
|
||||
# which would then ask host B again, etc.
|
||||
recursive:
|
||||
|
||||
# Enable recursive lookup globally
|
||||
enabled: true
|
||||
|
||||
# Whitelist of CIDR that will trigger a recursive lookup.
|
||||
# The default list includes all private IPv4 address and the IPv6 loopback.
|
||||
allowedCidr:
|
||||
- '127.0.0.0/8'
|
||||
- '10.0.0.0/8'
|
||||
- '172.16.0.0/12'
|
||||
- '192.168.0.0/16'
|
||||
- '::1/128'
|
||||
|
||||
# In case no binding is found, query an application server which implements the single lookup end-point
|
||||
# to return bridge virtual user that would allow the user to be contacted directly by the said bridge.
|
||||
#
|
||||
# If a binding is returned, the application server is not expected to sign the message as it is not meant to be
|
||||
# reachable from the outside.
|
||||
# If a signature is provided, it will be discarded/replaced by this IS implementation (to be implemented).
|
||||
#
|
||||
# IMPORTANT: This bypass the regular Invite system of the Homeserver. It will be up to the Application Server
|
||||
# to handle such invite. Also, if the bridged user were to actually join Matrix later, or if a 3PID binding is found
|
||||
# room rights and history would not be transferred, as it would appear as a regular Matrix user to the Homeserver.
|
||||
#
|
||||
# This configuration is only helpful for Application Services that want to overwrite bridging for 3PID that are
|
||||
# handled by the Homeserver. Do not enable unless the Application Server specifically supports it!
|
||||
bridge:
|
||||
|
||||
# Enable unknown 3PID bridging globally
|
||||
enabled: false
|
||||
|
||||
# Enable unknown 3PID bridging for hosts that are allowed to perform recursive lookups.
|
||||
# Leaving this setting to true is highly recommended in a standard setup, unless this Identity Server
|
||||
# is meant to always return a virtual user MXID even for the outside world.
|
||||
recursiveOnly: true
|
||||
|
||||
# This mechanism can handle the following scenarios:
|
||||
#
|
||||
# - Single Application Server for all 3PID types: only configure the server value, comment out the rest.
|
||||
#
|
||||
# - Specific Application Server for some 3PID types, default server for the rest: configure the server value and
|
||||
# each specific 3PID type.
|
||||
#
|
||||
# - Only specific 3PID types: do not configure the server value or leave it empty/blank, configure each specific
|
||||
# 3PID type.
|
||||
|
||||
# Default application server to use for all 3PID types. Remove config item or leave empty/blank to disable.
|
||||
server: ''
|
||||
|
||||
# Configure each 3PID type with a specific application server. Remove config item or leave empty/blank to disable.
|
||||
mappings:
|
||||
email: 'http://localhost:8091'
|
||||
msisdn: ''
|
||||
#############################
|
||||
# Signing keys config items #
|
||||
#############################
|
||||
# Absolute path for the Identity Server signing key.
|
||||
# During testing, /var/tmp/mxisd.key is a possible value
|
||||
#
|
||||
# For production, use a stable location like:
|
||||
# - /var/opt/mxisd/sign.key
|
||||
# - /var/local/mxisd/sign.key
|
||||
# - /var/lib/mxisd/sign.key
|
||||
key.path: '/path/to/sign.key'
|
||||
|
||||
|
||||
|
||||
ldap:
|
||||
enabled: false
|
||||
tls: false
|
||||
host: 'localhost'
|
||||
port: 389
|
||||
bindDn: 'CN=Matrix Identity Server,CN=Users,DC=example,DC=org'
|
||||
bindPassword: 'password'
|
||||
baseDn: 'CN=Users,DC=example,DC=org'
|
||||
#################################
|
||||
# Recurisve lookup config items #
|
||||
#################################
|
||||
# Configuration items for recursion-type of lookup
|
||||
#
|
||||
# Lookup access are divided into two types:
|
||||
# - Local
|
||||
# - Remote
|
||||
#
|
||||
# This is similar to DNS lookup and recursion and is therefore prone to the same vulnerabilities.
|
||||
# By default, only non-public hosts are allowed to perform recursive lookup.
|
||||
#
|
||||
# This will also prevent very basic endless loops where host A ask host B, which in turn is configured to ask host A,
|
||||
# which would then ask host B again, etc.
|
||||
|
||||
# How should we resolve the Matrix ID in case of a match using the attribute.
|
||||
#
|
||||
# The following type are supported:
|
||||
# - uid : the attribute only contains the UID part of the Matrix ID. e.g. 'john.doe' in @john.doe:example.org
|
||||
# - mxid : the attribute contains the full Matrix ID - e.g. '@john.doe:example.org'
|
||||
type: 'uid'
|
||||
# Enable recursive lookup globally
|
||||
#
|
||||
#lookup.recursive.enabled: true
|
||||
|
||||
# The attribute containing the binding itself. This value will be used differently depending on the type.
|
||||
#
|
||||
# /!\ This should match the synapse LDAP Authenticator 'uid' configuration /!\
|
||||
#
|
||||
# Typical values:
|
||||
# - For type 'uid': 'userPrincipalName' or 'uid' or 'saMAccountName'
|
||||
# - For type 'mxid', regardless of the directory type, we recommend using 'pager' as it is a standard attribute and
|
||||
# is typically not used.
|
||||
attribute: 'userPrincipalName'
|
||||
|
||||
# Configure each 3PID type with a dedicated query.
|
||||
mappings:
|
||||
email: "(|(mailPrimaryAddress=%3pid)(mail=%3pid)(otherMailbox=%3pid))"
|
||||
# Whitelist of CIDR that will trigger a recursive lookup.
|
||||
# The default list includes all private IPv4 address and the IPv6 loopback.
|
||||
#
|
||||
#lookup.recursive.allowedCidr:
|
||||
# - '127.0.0.0/8'
|
||||
# - '10.0.0.0/8'
|
||||
# - '172.16.0.0/12'
|
||||
# - '192.168.0.0/16'
|
||||
# - '::1/128'
|
||||
|
||||
# Phone numbers query.
|
||||
#
|
||||
# Phone numbers use the MSISDN format: https://en.wikipedia.org/wiki/MSISDN
|
||||
# This format does not include international prefix (+ or 00) and therefore has to be put in the query.
|
||||
# Adapt this to your needs for each attribute.
|
||||
msisdn: "(|(telephoneNumber=+%3pid)(mobile=+%3pid)(homePhone=+%3pid)(otherTelephone=+%3pid)(otherMobile=+%3pid)(otherHomePhone=+%3pid))"
|
||||
|
||||
# In case no binding is found, query an application server which implements the single lookup end-point
|
||||
# to return bridge virtual user that would allow the user to be contacted directly by the said bridge.
|
||||
#
|
||||
# If a binding is returned, the application server is not expected to sign the message as it is not meant to be
|
||||
# reachable from the outside.
|
||||
# If a signature is provided, it will be discarded/replaced by this IS implementation (to be implemented).
|
||||
#
|
||||
# IMPORTANT: This bypass the regular Invite system of the Homeserver. It will be up to the Application Server
|
||||
# to handle such invite. Also, if the bridged user were to actually join Matrix later, or if a 3PID binding is found
|
||||
# room rights and history would not be transferred, as it would appear as a regular Matrix user to the Homeserver.
|
||||
#
|
||||
# This configuration is only helpful for Application Services that want to overwrite bridging for 3PID that are
|
||||
# handled by the Homeserver. Do not enable unless the Application Server specifically supports it!
|
||||
|
||||
# Enable unknown 3PID bridging globally
|
||||
#
|
||||
#lookup.recursive.bridge.enabled: false
|
||||
|
||||
|
||||
# Enable unknown 3PID bridging for hosts that are allowed to perform recursive lookups.
|
||||
# Leaving this setting to true is highly recommended in a standard setup, unless this Identity Server
|
||||
# is meant to always return a virtual user MXID even for the outside world.
|
||||
#
|
||||
#lookup.recursive.bridge.recursiveOnly: true
|
||||
|
||||
|
||||
# This mechanism can handle the following scenarios:
|
||||
#
|
||||
# - Single Application Server for all 3PID types: only configure the server value, comment out the rest.
|
||||
#
|
||||
# - Specific Application Server for some 3PID types, default server for the rest: configure the server value and
|
||||
# each specific 3PID type.
|
||||
#
|
||||
# - Only specific 3PID types: do not configure the server value or leave it empty/blank, configure each specific
|
||||
# 3PID type.
|
||||
|
||||
# Default application server to use for all 3PID types. Remove config item or leave empty/blank to disable.
|
||||
#
|
||||
#lookup.recursive.bridge.server: ''
|
||||
|
||||
|
||||
# Configure each 3PID type with a specific application server. Remove config item or leave empty/blank to disable.
|
||||
#
|
||||
#lookup.recursive.bridge.mappings.email: 'http://localhost:8091'
|
||||
#lookup.recursive.bridge.mappings.msisdn: ''
|
||||
|
||||
|
||||
|
||||
forward:
|
||||
#####################
|
||||
# LDAP config items #
|
||||
#####################
|
||||
# Global enable/disable switch
|
||||
#
|
||||
#ldap.enabled: false
|
||||
|
||||
# List of forwarders to use to try to match a 3PID.
|
||||
#
|
||||
# Each server will be tried in the given order, going to the next if no binding was found or an error occurred.
|
||||
# These are the current root Identity Servers of the Matrix network.
|
||||
servers:
|
||||
- "https://matrix.org"
|
||||
- "https://vector.im"
|
||||
|
||||
#### Connection related config items
|
||||
# If the connection should be secure
|
||||
#
|
||||
#ldap.connection.tls: false
|
||||
|
||||
|
||||
# Host to connect to
|
||||
#
|
||||
#ldap.connection.host: 'localhost'
|
||||
|
||||
|
||||
# Port to connect to
|
||||
#
|
||||
#ldap.connection.port: 389
|
||||
|
||||
|
||||
# Bind DN for the connection.
|
||||
#
|
||||
# If Bind DN and password are empty, anonymous authentication is performed
|
||||
#
|
||||
#ldap.connection.bindDn: 'CN=Matrix Identity Server,CN=Users,DC=example,DC=org'
|
||||
|
||||
|
||||
# Bind password for the connection.
|
||||
#
|
||||
#ldap.connection.bindPassword: 'password'
|
||||
|
||||
|
||||
# Base DN used in all queries
|
||||
#
|
||||
#ldap.connection.baseDn: 'CN=Users,DC=example,DC=org'
|
||||
|
||||
|
||||
#### How to map Matrix attributes with LDAP attributes when performing lookup/auth
|
||||
#
|
||||
# How should we resolve the Matrix ID in case of a match using the attribute.
|
||||
#
|
||||
# The following type are supported:
|
||||
# - uid : the attribute only contains the UID part of the Matrix ID. e.g. 'john.doe' in @john.doe:example.org
|
||||
# - mxid : the attribute contains the full Matrix ID - e.g. '@john.doe:example.org'
|
||||
#
|
||||
#ldap.attribute.uid.type: 'uid'
|
||||
|
||||
|
||||
# The attribute containing the binding itself. This value will be used differently depending on the type.
|
||||
#
|
||||
# /!\ This should match the synapse LDAP Authenticator 'uid' configuration /!\
|
||||
#
|
||||
# Typical values:
|
||||
# - For type 'uid': 'userPrincipalName' or 'uid' or 'saMAccountName'
|
||||
# - For type 'mxid', regardless of the directory type, we recommend using 'pager' as it is a standard attribute and
|
||||
# is typically not used.
|
||||
#
|
||||
#ldap.attribute.uid.value: 'userPrincipalName'
|
||||
|
||||
|
||||
# The display name of the user
|
||||
#
|
||||
#ldap.attribute.name: 'displayName'
|
||||
|
||||
|
||||
#### Configuration section relating the authentication of users performed via LDAP.
|
||||
#
|
||||
# This can be done using the REST Auth module for synapse and pointing it to the identity server.
|
||||
# See https://github.com/kamax-io/matrix-synapse-rest-auth
|
||||
#
|
||||
# During authentication, What to filter potential users by, typically by using a dedicated group.
|
||||
# If this value is not set, login check will be performed for all entities within the LDAP
|
||||
#
|
||||
# Example: (memberOf=CN=Matrix Users,CN=Users,DC=example,DC=org)
|
||||
#
|
||||
#ldap.auth.filter: ''
|
||||
|
||||
|
||||
#### Configuration section relating to identity lookups
|
||||
#
|
||||
# E-mail query
|
||||
#
|
||||
#ldap.identity.medium.email: "(|(mailPrimaryAddress=%3pid)(mail=%3pid)(otherMailbox=%3pid))"
|
||||
|
||||
|
||||
# Phone numbers query
|
||||
#
|
||||
# Phone numbers use the MSISDN format: https://en.wikipedia.org/wiki/MSISDN
|
||||
# This format does not include international prefix (+ or 00) and therefore has to be put in the query.
|
||||
# Adapt this to your needs for each attribute.
|
||||
#
|
||||
#ldap.identity.medium.msisdn: "(|(telephoneNumber=+%3pid)(mobile=+%3pid)(homePhone=+%3pid)(otherTelephone=+%3pid)(otherMobile=+%3pid)(otherHomePhone=+%3pid))"
|
||||
|
||||
|
||||
|
||||
############################
|
||||
# SQL Provider config item #
|
||||
############################
|
||||
#
|
||||
# Example configuration to integrate with synapse SQLite DB (default configuration)
|
||||
#
|
||||
#sql.enabled: true
|
||||
#sql.type: 'sqlite'
|
||||
#sql.connection: '/var/lib/matrix-synapse/homeserver.db'
|
||||
|
||||
|
||||
#
|
||||
# Example configuration to integrate with synapse PostgreSQL DB
|
||||
#sql.enabled: true
|
||||
#sql.type: 'postgresql'
|
||||
#sql.connection: '//dnsOrIpToServer/dbName?user=synapseDbUser&password=synapseDbPassword'
|
||||
|
||||
|
||||
#
|
||||
# Configuration for an arbitrary server with arbitrary driver
|
||||
#
|
||||
# sql.identity.type possible values:
|
||||
# - uid Returned value is the localpart of the Matrix ID
|
||||
# - mxid Full Matrix ID, including domain
|
||||
#
|
||||
# sql.identity.query MUST contain a column with label 'uid'
|
||||
#
|
||||
# If you would like to overwrite the global lookup query for specific medium type,
|
||||
# add a config item (see below for example) in the following format
|
||||
# sql.identity.medium.theMediumIdYouWant: 'the query'
|
||||
|
||||
#sql.enabled: true
|
||||
#sql.type: 'jdbcDriverName'
|
||||
#sql.connection: '//dnsOrIpToServer/dbName?user=synapseDbUser&password=synapseDbPassword'
|
||||
#sql.identity.type: 'mxid'
|
||||
#sql.identity.query: 'SELECT raw AS uid FROM table WHERE medium = ? AND address = ?'
|
||||
#sql.identity.medium.email: 'SELECT raw AS uid FROM emailTable WHERE address = ?'
|
||||
|
||||
|
||||
|
||||
#######################################
|
||||
# Lookup queries forward config items #
|
||||
#######################################
|
||||
# List of forwarders to use to try to match a 3PID.
|
||||
#
|
||||
# Each server will be tried in the given order, going to the next if no binding was found or an error occurred.
|
||||
# These are the current root Identity Servers of the Matrix network.
|
||||
#
|
||||
#forward.servers:
|
||||
# - "https://matrix.org"
|
||||
# - "https://vector.im"
|
||||
|
||||
|
||||
|
||||
#############################
|
||||
# 3PID invites config items #
|
||||
#############################
|
||||
#
|
||||
#### E-mail invite sender
|
||||
#
|
||||
# SMTP host
|
||||
invite.sender.email.host: "smtp.example.org"
|
||||
|
||||
|
||||
# SMTP port
|
||||
invite.sender.email.port: 587
|
||||
|
||||
|
||||
# TLS mode for the connection.
|
||||
#
|
||||
# Possible values:
|
||||
# 0 Disable TLS entirely
|
||||
# 1 Enable TLS if supported by server
|
||||
# 2 Force TLS and fail if not available
|
||||
#
|
||||
#invite.sender.email.tls: 1
|
||||
|
||||
|
||||
# Login for SMTP
|
||||
invite.sender.email.login: "matrix-identity@example.org"
|
||||
|
||||
|
||||
# Password for the account
|
||||
invite.sender.email.password: "ThePassword"
|
||||
|
||||
|
||||
# The e-mail to send as. If empty, will be the same as login
|
||||
invite.sender.email.email: "matrix-identity@example.org"
|
||||
|
||||
|
||||
# The display name used in the e-mail
|
||||
#
|
||||
#invite.sender.email.name: "mxisd Identity Server"
|
||||
|
||||
|
||||
# The E-mail template to use, using built-in template by default
|
||||
#
|
||||
# The template is expected to be a full e-mail body, including client headers, using MIME and UTF-8 encoding.
|
||||
# The following headers will be set by mxisd directly and should not be present in the template:
|
||||
# - From
|
||||
# - To
|
||||
# - Date
|
||||
# - Message-Id
|
||||
# - X-Mailer
|
||||
#
|
||||
# The following placeholders are available:
|
||||
# - %DOMAIN% Domain name as per server.name config item
|
||||
# - %DOMAIN_PRETTY% Word capitalize version of the domain. e.g. example.org -> Example.org
|
||||
# - %FROM_EMAIL% Value of this section's email config item
|
||||
# - %FROM_NAME% Value of this section's name config item
|
||||
# - %SENDER_ID% Matrix ID of the invitation sender
|
||||
# - %SENDER_NAME% Display name of the invitation sender, empty if not available
|
||||
# - %SENDER_NAME_OR_ID% Value of %SENDER_NAME% or, if empty, value of %SENDER_ID%
|
||||
# - %INVITE_MEDIUM% Medium of the invite (e.g. email, msisdn)
|
||||
# - %INVITE_ADDRESS% Address used to invite
|
||||
# - %ROOM_ID% ID of the room where the invitation took place
|
||||
# - %ROOM_NAME% Name of the room, empty if not available
|
||||
# - %ROOM_NAME_OR_ID% Value of %ROOM_NAME% or, if empty, value of %ROOM_ID%
|
||||
#
|
||||
#invite.sender.email.template: "/absolute/path/to/file"
|
||||
|
||||
|
||||
|
||||
############################
|
||||
# Persistence config items #
|
||||
############################
|
||||
|
||||
# Configure the storage backend, usually a DB
|
||||
# Possible built-in values:
|
||||
# sqlite SQLite backend, default
|
||||
#
|
||||
#storage.backend: 'sqlite'
|
||||
|
||||
|
||||
#### Generic SQLite provider config
|
||||
#
|
||||
# Path to the SQLite DB file, required if SQLite backend is chosen
|
||||
#
|
||||
# Examples:
|
||||
# - /var/opt/mxisd/mxisd.db
|
||||
# - /var/local/mxisd/mxisd.db
|
||||
# - /var/lib/mxisd/mxisd.db
|
||||
#
|
||||
storage.provider.sqlite.database: '/path/to/mxisd.db'
|
||||
|
||||
|
||||
|
||||
######################
|
||||
# DNS-related config #
|
||||
######################
|
||||
# The domain to overwrite
|
||||
#
|
||||
#dns.overwrite.homeserver.name: 'example.org'
|
||||
|
||||
|
||||
# - 'env' from environment variable specified by value
|
||||
# - any other value will use the value as-is as host
|
||||
#
|
||||
#dns.overwrite.homeserver.type: 'raw'
|
||||
|
||||
|
||||
# The value to use, depending on the type.
|
||||
# Protocol will always be HTTPS
|
||||
#
|
||||
#dns.overwrite.homeserver.value: 'localhost:8448'
|
||||
|
72
build.gradle
72
build.gradle
@@ -40,6 +40,9 @@ def debBuildConfPath = "${debBuildBasePath}${debConfPath}"
|
||||
def debBuildDataPath = "${debBuildBasePath}${debDataPath}"
|
||||
def debBuildSystemdPath = "${debBuildBasePath}${debSystemdPath}"
|
||||
|
||||
def dockerImageName = "kamax/mxisd"
|
||||
def dockerImageTag = "${dockerImageName}:${gitVersion()}"
|
||||
|
||||
String gitVersion() {
|
||||
def versionPattern = Pattern.compile("v(\\d+\\.)?(\\d+\\.)?(\\d+)(-.*)?")
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream()
|
||||
@@ -62,6 +65,7 @@ buildscript {
|
||||
}
|
||||
|
||||
repositories {
|
||||
maven { url "https://kamax.io/maven/releases/" }
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
@@ -75,11 +79,17 @@ dependencies {
|
||||
// Spring Boot - standalone app
|
||||
compile 'org.springframework.boot:spring-boot-starter-web:1.5.3.RELEASE'
|
||||
|
||||
// Thymeleaf for HTML templates
|
||||
compile "org.springframework.boot:spring-boot-starter-thymeleaf:1.5.3.RELEASE"
|
||||
|
||||
// Matrix Java SDK
|
||||
compile 'io.kamax:matrix-java-sdk:0.0.2'
|
||||
|
||||
// ed25519 handling
|
||||
compile 'net.i2p.crypto:eddsa:0.1.0'
|
||||
|
||||
// LDAP connector
|
||||
compile 'org.apache.directory.api:api-all:1.0.0-RC2'
|
||||
compile 'org.apache.directory.api:api-all:1.0.0'
|
||||
|
||||
// DNS lookups
|
||||
compile 'dnsjava:dnsjava:2.1.8'
|
||||
@@ -93,7 +103,24 @@ dependencies {
|
||||
// Phone numbers validation
|
||||
compile 'com.googlecode.libphonenumber:libphonenumber:8.7.1'
|
||||
|
||||
// E-mail sending
|
||||
compile 'com.sun.mail:javax.mail:1.5.6'
|
||||
compile 'javax.mail:javax.mail-api:1.5.6'
|
||||
|
||||
// Google Firebase Authentication backend
|
||||
compile 'com.google.firebase:firebase-admin:5.3.0'
|
||||
|
||||
// ORMLite
|
||||
compile 'com.j256.ormlite:ormlite-jdbc:5.0'
|
||||
|
||||
// SQLite
|
||||
compile 'org.xerial:sqlite-jdbc:3.20.0'
|
||||
|
||||
// PostgreSQL
|
||||
compile 'org.postgresql:postgresql:42.1.4'
|
||||
|
||||
testCompile 'junit:junit:4.12'
|
||||
testCompile 'com.github.tomakehurst:wiremock:2.8.0'
|
||||
}
|
||||
|
||||
springBoot {
|
||||
@@ -104,6 +131,17 @@ springBoot {
|
||||
]
|
||||
}
|
||||
|
||||
processResources {
|
||||
doLast {
|
||||
copy {
|
||||
from('build/resources/main/application.yaml') {
|
||||
rename 'application.yaml', 'mxisd.yaml'
|
||||
}
|
||||
into 'build/resources/main'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task buildDeb(dependsOn: build) {
|
||||
doLast {
|
||||
def v = gitVersion()
|
||||
@@ -133,10 +171,16 @@ task buildDeb(dependsOn: build) {
|
||||
into debBuildConfPath
|
||||
}
|
||||
|
||||
ant.replace(
|
||||
ant.replaceregexp(
|
||||
file: "${debBuildConfPath}/${debConfFileName}",
|
||||
token: '%SIGNING_KEYS_PATH%',
|
||||
value: "${debDataPath}/signing.key"
|
||||
match: "key.path:(.*)",
|
||||
replace: "key.path: '${debDataPath}/signing.key'"
|
||||
)
|
||||
|
||||
ant.replaceregexp(
|
||||
file: "${debBuildConfPath}/${debConfFileName}",
|
||||
match: "storage.provider.sqlite.database:(.*)",
|
||||
replace: "storage.provider.sqlite.database: '${debDataPath}/mxisd.db'"
|
||||
)
|
||||
|
||||
copy {
|
||||
@@ -182,3 +226,23 @@ task buildDeb(dependsOn: build) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task dockerBuild(type: Exec, dependsOn: build) {
|
||||
commandLine 'docker', 'build', '-t', dockerImageTag, project.rootDir
|
||||
|
||||
doLast {
|
||||
exec {
|
||||
commandLine 'docker', 'tag', dockerImageTag, "${dockerImageName}:latest-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
task dockerPush(type: Exec) {
|
||||
commandLine 'docker', 'push', dockerImageTag
|
||||
|
||||
doLast {
|
||||
exec {
|
||||
commandLine 'docker', 'push', "${dockerImageName}:latest-dev"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
178
docs/backends/rest.md
Normal file
178
docs/backends/rest.md
Normal file
@@ -0,0 +1,178 @@
|
||||
# REST backend
|
||||
The REST backend allows you to query identity data in existing webapps, like:
|
||||
- Forums (phpBB, Discourse, etc.)
|
||||
- Custom Identity stores (Keycloak, ...)
|
||||
- CRMs (Wordpress, ...)
|
||||
- self-hosted clouds (Nextcloud, ownCloud, ...)
|
||||
|
||||
It supports the following mxisd flows:
|
||||
- Identity lookup
|
||||
- Authentication
|
||||
|
||||
To integrate this backend with your webapp, you will need to implement three specific REST endpoints detailed below.
|
||||
|
||||
|
||||
## Configuration
|
||||
| Key | Default | Description |
|
||||
---------------------------------|---------------------------------------|------------------------------------------------------|
|
||||
| rest.enabled | false | Globally enable/disable the REST backend |
|
||||
| rest.host | *empty* | Default base URL to use for the different endpoints. |
|
||||
| rest.endpoints.auth | /_mxisd/identity/api/v1/auth | Endpoint to validate credentials |
|
||||
| rest.endpoints.identity.single | /_mxisd/identity/api/v1/lookup/single | Endpoint to query a single 3PID |
|
||||
| rest.endpoints.identity.bulk | /_mxisd/identity/api/v1/lookup/bulk | Endpoint to query a list of 3PID |
|
||||
|
||||
Endpoint values can handle two formats:
|
||||
- URL Path starting with `/` that gets happened to the `rest.host`
|
||||
- Full URL, if you want each endpoint to go to a specific server/protocol/port
|
||||
|
||||
`rest.host` is only mandatory if at least one endpoint is not a full URL.
|
||||
|
||||
## Endpoints
|
||||
### Authenticate
|
||||
Configured with `rest.endpoints.auth`
|
||||
|
||||
HTTP method: `POST`
|
||||
Encoding: JSON UTF-8
|
||||
|
||||
#### Request Body
|
||||
```
|
||||
{
|
||||
"auth": {
|
||||
"mxid": "@john.doe:example.org",
|
||||
"localpart": "john.doe",
|
||||
"domain": "example.org",
|
||||
"password": "passwordOfTheUser"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Body
|
||||
If the authentication fails:
|
||||
```
|
||||
{
|
||||
"auth": {
|
||||
"success": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If the authentication succeed:
|
||||
- `auth.id` supported values: `localpart`, `mxid`
|
||||
- `auth.profile` and any sub-member are all optional
|
||||
```
|
||||
{
|
||||
"auth": {
|
||||
"success": true,
|
||||
"id": {
|
||||
"type": "localpart",
|
||||
"value": "john"
|
||||
},
|
||||
"profile": {
|
||||
"display_name": "John Doe",
|
||||
"three_pids": [
|
||||
{
|
||||
"medium": "email",
|
||||
"address": "john.doe@example.org"
|
||||
},
|
||||
{
|
||||
"medium": "msisdn",
|
||||
"address": "123456789"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Lookup
|
||||
#### Single
|
||||
Configured with `rest.endpoints.identity.single`
|
||||
|
||||
HTTP method: `POST`
|
||||
Encoding: JSON UTF-8
|
||||
|
||||
#### Request Body
|
||||
```
|
||||
{
|
||||
"lookup": {
|
||||
"medium": "email",
|
||||
"address": "john.doe@example.org"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Body
|
||||
If a match was found:
|
||||
- `lookup.id.type` supported values: `localpart`, `mxid`
|
||||
```
|
||||
{
|
||||
"lookup": {
|
||||
"medium": "email",
|
||||
"address": "john.doe@example.org",
|
||||
"id": {
|
||||
"type": "mxid",
|
||||
"value": "@john:example.org"
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
If no match was found:
|
||||
```
|
||||
{}
|
||||
```
|
||||
|
||||
#### Bulk
|
||||
Configured with `rest.endpoints.identity.bulk`
|
||||
|
||||
HTTP method: `POST`
|
||||
Encoding: JSON UTF-8
|
||||
|
||||
#### Request Body
|
||||
```
|
||||
{
|
||||
"lookup": [
|
||||
{
|
||||
"medium": "email",
|
||||
"address": "john.doe@example.org"
|
||||
},
|
||||
{
|
||||
"medium": "msisdn",
|
||||
"address": "123456789"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### Response Body
|
||||
For all entries where a match was found:
|
||||
- `lookup[].id.type` supported values: `localpart`, `mxid`
|
||||
```
|
||||
{
|
||||
"lookup": [
|
||||
{
|
||||
"medium": "email",
|
||||
"address": "john.doe@example.org",
|
||||
"id": {
|
||||
"type": "localpart",
|
||||
"value": "john"
|
||||
}
|
||||
},
|
||||
{
|
||||
"medium": "msisdn",
|
||||
"address": "123456789",
|
||||
"id": {
|
||||
"type": "mxid",
|
||||
"value": "@jane:example.org"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
If no match was found:
|
||||
```
|
||||
{
|
||||
"lookup": []
|
||||
}
|
||||
```
|
335
docs/sessions/3pid.md
Normal file
335
docs/sessions/3pid.md
Normal file
@@ -0,0 +1,335 @@
|
||||
# 3PID Sessions
|
||||
- [Overview](#overview)
|
||||
- [Purpose](#purpose)
|
||||
- [Federation](#federation)
|
||||
- [3PID scope](#3pid-scope)
|
||||
- [Session scope](#session-scope)
|
||||
- [Notifications](#notifications)
|
||||
- [Email](#email)
|
||||
- [Usage](#usage)
|
||||
- [Configuration](#configuration)
|
||||
- [Scenarios](#scenarios)
|
||||
- [Default](#default)
|
||||
- [Local sessions only](#local-sessions-only)
|
||||
- [Remote sessions only](#remote-sessions-only)
|
||||
- [Sessions disabled](#sessions-disabled)
|
||||
|
||||
## Overview
|
||||
When adding an email, a phone number or any other kind of 3PID (Third-Party Identifier),
|
||||
the identity server is called to validate the 3PID.
|
||||
|
||||
Once this 3PID is validated, the Homeserver will publish the user Matrix ID on the Identity Server and
|
||||
add this 3PID to the Matrix account which initiated the request.
|
||||
|
||||
## Purpose
|
||||
This serves two purposes:
|
||||
- Add the 3PID as an administrative/login info for the Homeserver directly
|
||||
- Publish, or *Bind*, the 3PID so it can be queried from Homeservers and clients when inviting someone in a room
|
||||
by a 3PID, allowing it to be resolved to a Matrix ID.
|
||||
|
||||
## Federation
|
||||
Federation is based on the principle that one can get a domain name and serve services and information within that
|
||||
domain namespace in a way which can be discovered following a specific protocol or specification.
|
||||
|
||||
In the Matrix eco-system, some 3PID can be federated (e.g. emails) while some others cannot (phone numbers).
|
||||
Also, Matrix users might add 3PIDs that would not point to the Identity server that actually holds the 3PID binding.
|
||||
|
||||
Example: a user from Homeserver `example.org` adds an email `john@gmail.com`.
|
||||
If a federated lookup was performed, Identity servers would try to find the 3PID bind at the `gmail.com` server, and
|
||||
not `example.org`.
|
||||
|
||||
To allow global publishing of 3PID bindings to be found anywhere within the current protocol specification, one would
|
||||
perform a *Remote session* and *Remote bind*, effectively starting a new 3PID session with another Identity server on
|
||||
behalf of the user.
|
||||
To ensure lookup works consistency within the current Matrix network, the central Matrix.org Identity Server should be
|
||||
used to store *remote* sessions and binds.
|
||||
|
||||
On the flip side, at the time of writing, the Matrix specification and the central Matrix.org servers do not allow to
|
||||
remote a 3PID bind. This means that once a 3PID is published (email, phone number, etc.), it cannot be easily remove
|
||||
and would require contacting the Matrix.org administrators for each bind individually.
|
||||
This poses a privacy, control and security concern, especially for groups/corporations that want to keep a tight control
|
||||
on where such identifiers can be made publicly visible.
|
||||
|
||||
To ensure full control, validation management rely on two concepts:
|
||||
- The scope of 3PID being validated
|
||||
- The scope of 3PID sessions that should be possible/offered
|
||||
|
||||
### 3PID scope
|
||||
3PID can either be scoped as local or remote.
|
||||
|
||||
Local means that they can looked up using federation and that such federation call would end up on the local
|
||||
Identity Server.
|
||||
Remote means that they cannot be lookup using federation or that a federation call would not end up on the local
|
||||
Identity Server.
|
||||
|
||||
Email addresses can either be local or remote 3PID, depending on the domain. If the address is one from the configured
|
||||
domain in the Identity server, it will be scoped as local. If it is from another domain, it will be as remote.
|
||||
|
||||
Phone number can only be scoped as remote, since there is currently no way to perform DNS queries that would lead back
|
||||
to the Identity server who validated the phone number.
|
||||
|
||||
### Session scope
|
||||
Sessions can be scoped as:
|
||||
- Local only - validate 3PIDs directly, do not allow the creation of 3PID sessions on a remote Identity server.
|
||||
- Local and Remote - validate 3PIDs directly, offer users to option to also validate and bind 3PID on another server.
|
||||
- Remote only - validate and bind 3PIDs on another server, no validation or bind done locally.
|
||||
|
||||
---
|
||||
|
||||
**IMPORTANT NOTE:** mxisd does not store bindings directly. While a user can see its email, phone number or any other
|
||||
3PID in its settings/profile, it does **NOT** mean it is published anywhere and can be used to invite/search the user.
|
||||
Identity backends (LDAP, REST, SQL) are the ones holding such data.
|
||||
If you still want added arbitrary 3PIDs to be discoverable on your local server, you will need to link mxisd to your
|
||||
synapse DB to make it an Identity backend.
|
||||
|
||||
See the [Scenarios](#scenarios) for more info on how and why.
|
||||
|
||||
## Notifications
|
||||
3PIDs are validated by sending a pre-formatted message containing a token to that 3PID address, which must be given to the
|
||||
Identity server that received the request. This is usually done by means of a URL to visit for email or a short number
|
||||
received by SMS for phone numbers.
|
||||
|
||||
mxisd use two components for this:
|
||||
- Generator which produces the message to be sent with the necessary information the user needs to validate their session.
|
||||
- Connector which actually send the notification (e.g. SMTP for email).
|
||||
|
||||
Built-in generators and connectors for supported 3PID types:
|
||||
|
||||
### Email
|
||||
Generators:
|
||||
- Template
|
||||
|
||||
Connectors:
|
||||
- SMTP
|
||||
|
||||
|
||||
## Usage
|
||||
### Configuration
|
||||
The following example of configuration (incomplete extract) shows which items are relevant for 3PID sessions.
|
||||
|
||||
**IMPORTANT:** Most configuration items shown have default values and should not be included in your own configuration
|
||||
file unless you want to specifically overwrite them.
|
||||
Please refer to the full example config file to see which keys are mandatory and to be included in your configuration.
|
||||
```
|
||||
matrix:
|
||||
identity:
|
||||
servers:
|
||||
root: # Not to be included in config! Already present in default config!
|
||||
- 'https://matrix.org'
|
||||
|
||||
|
||||
threepid:
|
||||
medium:
|
||||
email:
|
||||
connector: 'smtp'
|
||||
generator: 'template'
|
||||
connectors:
|
||||
smtp:
|
||||
host: ''
|
||||
port: 587
|
||||
tls: 1
|
||||
login: ''
|
||||
password: ''
|
||||
generators:
|
||||
template: # Not to be included in config! Already present in default config!
|
||||
invite: 'classpath:email/invite-template.eml'
|
||||
session:
|
||||
validation:
|
||||
local: 'classpath:email/validate-local-template.eml'
|
||||
remote: 'classpath:email/validate-remote-template.eml'
|
||||
|
||||
session:
|
||||
policy:
|
||||
validation:
|
||||
enabled: true
|
||||
forLocal:
|
||||
enabled: true
|
||||
toLocal: true
|
||||
toRemote:
|
||||
enabled: true
|
||||
server: 'configExample' # Not to be included in config! Already present in default config!
|
||||
forRemote:
|
||||
enabled: true
|
||||
toLocal: false
|
||||
toRemote:
|
||||
enabled: true
|
||||
server: 'configExample' # Not to be included in config! Already present in default config!
|
||||
```
|
||||
|
||||
`matrix.identity.servers` is the namespace to configure arbitrary list of Identity servers with a label as parent key.
|
||||
In the above example, the list with label `configExample` contains a single server entry pointing to `https://matrix.org`.
|
||||
|
||||
**NOTE:** The server list is set to `root` by default and should typically NOT be included in your config.
|
||||
|
||||
Identity server entry can be of two format:
|
||||
- URL, bypassing any kind of domain and port discovery
|
||||
- Domain name as `string`, allowing federated discovery to take place.
|
||||
|
||||
The label can be used in other places of the configuration, allowing you to only declare Identity servers once.
|
||||
|
||||
---
|
||||
|
||||
`threepid.medium.<3PID>` is the namespace to configure 3PID specific items, not directly tied to any other component of
|
||||
mxisd.
|
||||
In the above example, only `email` is defined as 3PID type.
|
||||
|
||||
Each 3PID namespace comes with 4 configuration key allowing you to configure generators and connectors for notifications:
|
||||
- `connectors` is a configuration namespace to be used for any connector configuration. Child keys represent the unique
|
||||
ID for each connector.
|
||||
- `generators` is a configuration namespace to be used for any generator configuration. Child keys represent the unique
|
||||
ID for each generator.
|
||||
- `connector` is given the ID of the connector to be used at runtime.
|
||||
- `generator` is given the ID of the generator to be used at runtime.
|
||||
|
||||
In the above example, emails notifications are generated by the `template` module and sent with the `smtp` module.
|
||||
|
||||
mxisd comes with the following IDs built-in:
|
||||
**Connectors**
|
||||
- `smtp` for a basic SMTP connector, attempting STARTLS by default.
|
||||
|
||||
**Generators**
|
||||
- `template`, loading content from template files, using built-in mxisd templates by default.
|
||||
|
||||
---
|
||||
|
||||
`session.policy.validation` is the core configuration to control what users configured to use your Identity server
|
||||
are allowed to do in terms of 3PID sessions.
|
||||
|
||||
The policy is divided contains a global on/off switch for 3PID sessions using `.enabled`
|
||||
It is also divided into two sections: `forLocal` and `forRemote` which refers to the 3PID scopes.
|
||||
|
||||
Each scope is divided into three parts:
|
||||
- global on/off switch for 3PID sessions using `.enabled`
|
||||
- `toLocal` allowing or not local 3PID session validations
|
||||
- `toRemote` allowing or not remote 3PID session validations and to which server such sessions should be sent.
|
||||
`.server` takes a Matrix Identity server list label. Only the first server in the list is currently used.
|
||||
|
||||
If both `toLocal` and `toRemote` are enabled, the user will be offered to initiate a remote session once their 3PID
|
||||
locally validated.
|
||||
|
||||
### Scenarios
|
||||
It is important to keep in mind that mxisd does not create bindings, irrelevant if a user added a 3PID to their profile.
|
||||
Instead, when queried for bindings, mxisd will query Identity backends which are responsible to store this kind of information.
|
||||
|
||||
This has the side effect that any 3PID added to a user profile which is NOT within a configured and enabled Identity backend
|
||||
will simply not be usable for search or invites, **even on the same Homeserver!**
|
||||
mxisd does not store binds on purpose, as one of its primary goal is to ensure maximum compatibility with federation
|
||||
and the rest of the Matrix ecosystem is preserved.
|
||||
|
||||
Nonetheless, because mxisd also aims at offering support for tight control over identity data, it is possible to have
|
||||
such 3PID bindings available for search and invite queries on the local Homeserver by using the `SQL` backend and
|
||||
configuring it to use the synapse database. Support for `SQLite` and `PostgreSQL` is available.
|
||||
|
||||
See the [Local sessions only](#local-sessions-only) use case for more information on how to configure.
|
||||
|
||||
#### Default
|
||||
By default, mxisd allows the following:
|
||||
|
||||
| | Local Session | Remote Session |
|
||||
|----------------|-------|--------|
|
||||
| **Local 3PID** | Yes | Yes, offered |
|
||||
| **Remote 3PID** | No, Remote forced | Yes |
|
||||
|
||||
This is usually what people expect and will feel natural to users and does not involve further integration.
|
||||
|
||||
This allows to stay in control for e-mail addresses which domain matches your Matrix environment, still making them
|
||||
discoverable with federation but not recorded in a 3rd party Identity server which is not under your control.
|
||||
Users still get the possibility to publish globally their address if needed.
|
||||
|
||||
Other e-mail addresses and phone number will be redirected to remote sessions to ensure full compatibility with the Matrix
|
||||
ecosystem and other federated servers.
|
||||
|
||||
#### Local sessions only
|
||||
**NOTE:** This does not affect 3PID lookups (queries to find Matrix IDs) which will remain public due to limitation
|
||||
in the Matrix protocol.
|
||||
|
||||
This configuration ensures maximum confidentiality and privacy.
|
||||
Typical use cases:
|
||||
- Private Homeserver, not federated
|
||||
- Internal Homeserver without direct Internet access
|
||||
- Custom product based on Matrix which does not federate
|
||||
|
||||
No 3PID will be sent to a remote Identity server and all validation will be performed locally.
|
||||
On the flip side, people with *Remote* 3PID scopes will not be found from other servers.
|
||||
|
||||
Use the following values:
|
||||
```
|
||||
session:
|
||||
policy:
|
||||
validation:
|
||||
enabled: true
|
||||
forLocal:
|
||||
enabled: true
|
||||
toLocal: true
|
||||
toRemote:
|
||||
enabled: false
|
||||
forRemote:
|
||||
enabled: true
|
||||
toLocal: true
|
||||
toRemote:
|
||||
enabled: false
|
||||
```
|
||||
|
||||
**IMPORTANT**: When using local-only mode, you will also need to link mxisd to synapse if you want user searches and invites to work.
|
||||
To do so, add/edit the following configuration keys:
|
||||
```
|
||||
sql:
|
||||
enabled: true
|
||||
type: 'postgresql'
|
||||
connection: ''
|
||||
```
|
||||
- `sql.enabled` set to `true` to activate the SQL backend.
|
||||
- `sql.type` can be set to `sqlite` or `postgresql`, depending on your synapse setup.
|
||||
- `sql.connection` use a JDBC format which is appened after the `jdbc:type:` connection URI.
|
||||
Example values for each type:
|
||||
- `sqlite`: `/path/to/homeserver.db`
|
||||
- `postgresql`: `//localhost/database?user=synapse&password=synapse`
|
||||
|
||||
#### Remote sessions only
|
||||
This configuration ensures all 3PID are made public for maximum compatibility and reach within the Matrix ecosystem, at
|
||||
the cost of confidentiality and privacy.
|
||||
|
||||
Typical use cases:
|
||||
- Public Homeserver
|
||||
- Homeserver with registration enabled
|
||||
|
||||
Use the following values:
|
||||
```
|
||||
session:
|
||||
policy:
|
||||
validation:
|
||||
enabled: true
|
||||
forLocal:
|
||||
enabled: true
|
||||
toLocal: false
|
||||
toRemote:
|
||||
enabled: true
|
||||
forRemote:
|
||||
enabled: true
|
||||
toLocal: false
|
||||
toRemote:
|
||||
enabled: true
|
||||
```
|
||||
|
||||
#### Sessions disabled
|
||||
This configuration would disable 3PID session altogether, preventing users from adding emails and/or phone numbers to
|
||||
their profiles.
|
||||
This would be used if mxisd is also performing authentication for the Homeserver, typically with synapse and the
|
||||
[REST Auth module](https://github.com/kamax-io/matrix-synapse-rest-auth).
|
||||
|
||||
While this feature is not yet ready in the REST auth module, you would use this configuration mode to auto-populate 3PID
|
||||
at user login and prevent any further add.
|
||||
|
||||
**This mode comes with several important restrictions:**
|
||||
- This does not prevent users from removing 3PID from their profile. They would be unable to add them back!
|
||||
- This prevents users from initiating remote session to make their 3PID binds globally visible
|
||||
|
||||
It is therefore recommended to not fully disable sessions but instead restrict specific set of 3PID and Session scopes.
|
||||
|
||||
Use the following values to enable this mode:
|
||||
```
|
||||
session:
|
||||
policy:
|
||||
validation:
|
||||
enabled: false
|
||||
```
|
BIN
media/mx-id-icon-reverse.png
Normal file
BIN
media/mx-id-icon-reverse.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 8.6 KiB |
BIN
media/mx-id-icon.png
Normal file
BIN
media/mx-id-icon.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 5.7 KiB |
51
src/main/groovy/io/kamax/mxisd/ThreePid.java
Normal file
51
src/main/groovy/io/kamax/mxisd/ThreePid.java
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd;
|
||||
|
||||
// FIXME this should be in matrix-java-sdk
|
||||
public class ThreePid {
|
||||
|
||||
private String medium;
|
||||
private String address;
|
||||
|
||||
public ThreePid(ThreePid tpid) {
|
||||
this(tpid.getMedium(), tpid.getAddress());
|
||||
}
|
||||
|
||||
public ThreePid(String medium, String address) {
|
||||
this.medium = medium;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return getMedium() + ":" + getAddress();
|
||||
}
|
||||
|
||||
}
|
46
src/main/groovy/io/kamax/mxisd/UserID.java
Normal file
46
src/main/groovy/io/kamax/mxisd/UserID.java
Normal file
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd;
|
||||
|
||||
// FIXME consider integrating in matrix-java-sdk?
|
||||
public class UserID {
|
||||
|
||||
private String type;
|
||||
private String value;
|
||||
|
||||
protected UserID() {
|
||||
// stub for (de)serialization
|
||||
}
|
||||
|
||||
public UserID(String type, String value) {
|
||||
this.type = type;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
}
|
47
src/main/groovy/io/kamax/mxisd/UserIdType.java
Normal file
47
src/main/groovy/io/kamax/mxisd/UserIdType.java
Normal file
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
|
||||
// FIXME consider integrating in matrix-java-sdk?
|
||||
public enum UserIdType {
|
||||
|
||||
Localpart("localpart"),
|
||||
MatrixID("mxid"),
|
||||
EmailLocalpart("email_localpart"),
|
||||
Email("email");
|
||||
|
||||
private String id;
|
||||
|
||||
UserIdType(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public boolean is(String id) {
|
||||
return StringUtils.equalsIgnoreCase(this.id, id);
|
||||
}
|
||||
|
||||
}
|
93
src/main/groovy/io/kamax/mxisd/auth/AuthManager.java
Normal file
93
src/main/groovy/io/kamax/mxisd/auth/AuthManager.java
Normal file
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.auth;
|
||||
|
||||
import io.kamax.matrix.MatrixID;
|
||||
import io.kamax.matrix._MatrixID;
|
||||
import io.kamax.mxisd.ThreePid;
|
||||
import io.kamax.mxisd.UserIdType;
|
||||
import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
|
||||
import io.kamax.mxisd.auth.provider.BackendAuthResult;
|
||||
import io.kamax.mxisd.config.MatrixConfig;
|
||||
import io.kamax.mxisd.invitation.InvitationManager;
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class AuthManager {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(AuthManager.class);
|
||||
|
||||
@Autowired
|
||||
private List<AuthenticatorProvider> providers = new ArrayList<>();
|
||||
|
||||
@Autowired
|
||||
private MatrixConfig mxCfg;
|
||||
|
||||
@Autowired
|
||||
private InvitationManager invMgr;
|
||||
|
||||
public UserAuthResult authenticate(String id, String password) {
|
||||
_MatrixID mxid = new MatrixID(id);
|
||||
for (AuthenticatorProvider provider : providers) {
|
||||
if (!provider.isEnabled()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
BackendAuthResult result = provider.authenticate(mxid, password);
|
||||
if (result.isSuccess()) {
|
||||
|
||||
String mxId;
|
||||
if (UserIdType.Localpart.is(result.getId().getType())) {
|
||||
mxId = new MatrixID(result.getId().getValue(), mxCfg.getDomain()).getId();
|
||||
} else if (UserIdType.MatrixID.is(result.getId().getType())) {
|
||||
mxId = new MatrixID(result.getId().getValue()).getId();
|
||||
} else {
|
||||
log.warn("Unsupported User ID type {} for backend {}", result.getId().getType(), provider.getClass().getSimpleName());
|
||||
continue;
|
||||
}
|
||||
|
||||
UserAuthResult authResult = new UserAuthResult().success(mxId, result.getProfile().getDisplayName());
|
||||
for (ThreePid pid : result.getProfile().getThreePids()) {
|
||||
authResult.withThreePid(pid.getMedium(), pid.getAddress());
|
||||
}
|
||||
log.info("{} was authenticated by {}, publishing 3PID mappings, if any", id, provider.getClass().getSimpleName());
|
||||
for (ThreePid pid : authResult.getThreePids()) {
|
||||
log.info("Processing {} for {}", pid, id);
|
||||
invMgr.publishMappingIfInvited(new ThreePidMapping(pid, authResult.getMxid()));
|
||||
}
|
||||
|
||||
invMgr.lookupMappingsForInvites();
|
||||
|
||||
return authResult;
|
||||
}
|
||||
}
|
||||
|
||||
return new UserAuthResult().failure();
|
||||
}
|
||||
|
||||
}
|
91
src/main/groovy/io/kamax/mxisd/auth/UserAuthResult.java
Normal file
91
src/main/groovy/io/kamax/mxisd/auth/UserAuthResult.java
Normal file
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.auth;
|
||||
|
||||
import io.kamax.matrix.ThreePidMedium;
|
||||
import io.kamax.mxisd.ThreePid;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class UserAuthResult {
|
||||
|
||||
private boolean success;
|
||||
private String mxid;
|
||||
private String displayName;
|
||||
private List<ThreePid> threePids = new ArrayList<>();
|
||||
|
||||
public UserAuthResult failure() {
|
||||
success = false;
|
||||
mxid = null;
|
||||
displayName = null;
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public UserAuthResult success(String mxid, String displayName) {
|
||||
setSuccess(true);
|
||||
setMxid(mxid);
|
||||
setDisplayName(displayName);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(boolean success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
public String getMxid() {
|
||||
return mxid;
|
||||
}
|
||||
|
||||
public void setMxid(String mxid) {
|
||||
this.mxid = mxid;
|
||||
}
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public void setDisplayName(String displayName) {
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
public UserAuthResult withThreePid(ThreePidMedium medium, String address) {
|
||||
return withThreePid(medium.getId(), address);
|
||||
}
|
||||
|
||||
public UserAuthResult withThreePid(String medium, String address) {
|
||||
threePids.add(new ThreePid(medium, address));
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public List<ThreePid> getThreePids() {
|
||||
return Collections.unmodifiableList(threePids);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.auth.provider;
|
||||
|
||||
import io.kamax.matrix._MatrixID;
|
||||
|
||||
public interface AuthenticatorProvider {
|
||||
|
||||
boolean isEnabled();
|
||||
|
||||
BackendAuthResult authenticate(_MatrixID mxid, String password);
|
||||
|
||||
}
|
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.auth.provider;
|
||||
|
||||
import io.kamax.mxisd.ThreePid;
|
||||
import io.kamax.mxisd.UserID;
|
||||
import io.kamax.mxisd.UserIdType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class BackendAuthResult {
|
||||
|
||||
public static class BackendAuthProfile {
|
||||
|
||||
private String displayName;
|
||||
private List<ThreePid> threePids = new ArrayList<>();
|
||||
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
public List<ThreePid> getThreePids() {
|
||||
return threePids;
|
||||
}
|
||||
}
|
||||
|
||||
public static BackendAuthResult failure() {
|
||||
BackendAuthResult r = new BackendAuthResult();
|
||||
r.success = false;
|
||||
return r;
|
||||
}
|
||||
|
||||
public static BackendAuthResult success(String id, UserIdType type, String displayName) {
|
||||
return success(id, type.getId(), displayName);
|
||||
}
|
||||
|
||||
public static BackendAuthResult success(String id, String type, String displayName) {
|
||||
BackendAuthResult r = new BackendAuthResult();
|
||||
r.success = true;
|
||||
r.id = new UserID(type, id);
|
||||
r.profile = new BackendAuthProfile();
|
||||
r.profile.displayName = displayName;
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
private Boolean success;
|
||||
private UserID id;
|
||||
private BackendAuthProfile profile = new BackendAuthProfile();
|
||||
|
||||
public Boolean isSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public UserID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public BackendAuthProfile getProfile() {
|
||||
return profile;
|
||||
}
|
||||
|
||||
public BackendAuthResult withThreePid(ThreePid threePid) {
|
||||
this.profile.threePids.add(threePid);
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,193 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.firebase
|
||||
|
||||
import com.google.firebase.FirebaseApp
|
||||
import com.google.firebase.FirebaseOptions
|
||||
import com.google.firebase.auth.*
|
||||
import com.google.firebase.internal.NonNull
|
||||
import com.google.firebase.tasks.OnFailureListener
|
||||
import com.google.firebase.tasks.OnSuccessListener
|
||||
import io.kamax.matrix.ThreePidMedium
|
||||
import io.kamax.matrix._MatrixID
|
||||
import io.kamax.mxisd.ThreePid
|
||||
import io.kamax.mxisd.UserIdType
|
||||
import io.kamax.mxisd.auth.provider.AuthenticatorProvider
|
||||
import io.kamax.mxisd.auth.provider.BackendAuthResult
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.regex.Pattern
|
||||
|
||||
public class GoogleFirebaseAuthenticator implements AuthenticatorProvider {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(GoogleFirebaseAuthenticator.class);
|
||||
|
||||
private static final Pattern matrixIdLaxPattern = Pattern.compile("@(.*):(.+)"); // FIXME use matrix-java-sdk
|
||||
|
||||
private boolean isEnabled;
|
||||
private String domain;
|
||||
private FirebaseApp fbApp;
|
||||
private FirebaseAuth fbAuth;
|
||||
|
||||
private void waitOnLatch(BackendAuthResult result, CountDownLatch l, long timeout, TimeUnit unit, String purpose) {
|
||||
try {
|
||||
l.await(timeout, unit);
|
||||
} catch (InterruptedException e) {
|
||||
log.warn("Interrupted while waiting for " + purpose);
|
||||
result.failure();
|
||||
}
|
||||
}
|
||||
|
||||
public GoogleFirebaseAuthenticator(boolean isEnabled) {
|
||||
this.isEnabled = isEnabled;
|
||||
}
|
||||
|
||||
public GoogleFirebaseAuthenticator(String credsPath, String db, String domain) {
|
||||
this(true);
|
||||
this.domain = domain;
|
||||
try {
|
||||
fbApp = FirebaseApp.initializeApp(getOpts(credsPath, db), "AuthenticationProvider");
|
||||
fbAuth = FirebaseAuth.getInstance(fbApp);
|
||||
|
||||
log.info("Google Firebase Authentication is ready");
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error when initializing Firebase", e);
|
||||
}
|
||||
}
|
||||
|
||||
private FirebaseCredential getCreds(String credsPath) throws IOException {
|
||||
if (StringUtils.isNotBlank(credsPath)) {
|
||||
return FirebaseCredentials.fromCertificate(new FileInputStream(credsPath));
|
||||
} else {
|
||||
return FirebaseCredentials.applicationDefault();
|
||||
}
|
||||
}
|
||||
|
||||
private FirebaseOptions getOpts(String credsPath, String db) throws IOException {
|
||||
if (StringUtils.isBlank(db)) {
|
||||
throw new IllegalArgumentException("Firebase database is not configured");
|
||||
}
|
||||
|
||||
return new FirebaseOptions.Builder()
|
||||
.setCredential(getCreds(credsPath))
|
||||
.setDatabaseUrl(db)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
private void waitOnLatch(CountDownLatch l) {
|
||||
try {
|
||||
l.await(30, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
log.warn("Interrupted while waiting for Firebase auth check");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
|
||||
if (!isEnabled()) {
|
||||
throw new IllegalStateException();
|
||||
}
|
||||
|
||||
log.info("Trying to authenticate {}", mxid);
|
||||
|
||||
BackendAuthResult result = BackendAuthResult.failure();
|
||||
|
||||
String localpart = m.group(1);
|
||||
CountDownLatch l = new CountDownLatch(1);
|
||||
fbAuth.verifyIdToken(password).addOnSuccessListener(new OnSuccessListener<FirebaseToken>() {
|
||||
@Override
|
||||
void onSuccess(FirebaseToken token) {
|
||||
try {
|
||||
if (!StringUtils.equals(localpart, token.getUid())) {
|
||||
log.info("Failture to authenticate {}: Matrix ID localpart '{}' does not match Firebase UID '{}'", id, localpart, token.getUid());
|
||||
result = BackendAuthResult.failure();
|
||||
return;
|
||||
}
|
||||
|
||||
result = BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, token.getName());
|
||||
log.info("{} was successfully authenticated", mxid);
|
||||
log.info("Fetching profile for {}", mxid);
|
||||
CountDownLatch userRecordLatch = new CountDownLatch(1);
|
||||
fbAuth.getUser(token.getUid()).addOnSuccessListener(new OnSuccessListener<UserRecord>() {
|
||||
@Override
|
||||
void onSuccess(UserRecord user) {
|
||||
try {
|
||||
if (StringUtils.isNotBlank(user.getEmail())) {
|
||||
result.withThreePid(new ThreePid(ThreePidMedium.Email.getId(), user.getEmail()));
|
||||
}
|
||||
|
||||
if (StringUtils.isNotBlank(user.getPhoneNumber())) {
|
||||
result.withThreePid(new ThreePid(ThreePidMedium.PhoneNumber.getId(), user.getPhoneNumber()));
|
||||
}
|
||||
|
||||
} finally {
|
||||
userRecordLatch.countDown();
|
||||
}
|
||||
}
|
||||
}).addOnFailureListener(new OnFailureListener() {
|
||||
@Override
|
||||
void onFailure(@NonNull Exception e) {
|
||||
try {
|
||||
log.warn("Unable to fetch Firebase user profile for {}", mxid);
|
||||
result = BackendAuthResult.failure();
|
||||
} finally {
|
||||
userRecordLatch.countDown();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
waitOnLatch(result, userRecordLatch, 30, TimeUnit.SECONDS, "Firebase user profile");
|
||||
} finally {
|
||||
l.countDown()
|
||||
}
|
||||
}
|
||||
}).addOnFailureListener(new OnFailureListener() {
|
||||
@Override
|
||||
void onFailure(@NonNull Exception e) {
|
||||
try {
|
||||
if (e instanceof IllegalArgumentException) {
|
||||
log.info("Failure to authenticate {}: invalid firebase token", mxid);
|
||||
} else {
|
||||
log.info("Failure to authenticate {}: {}", id, e.getMessage(), e);
|
||||
log.info("Exception", e);
|
||||
}
|
||||
|
||||
result = BackendAuthResult.failure();
|
||||
} finally {
|
||||
l.countDown()
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
waitOnLatch(result, l, 30, TimeUnit.SECONDS, "Firebase auth check");
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.firebase
|
||||
|
||||
import com.google.firebase.FirebaseApp
|
||||
import com.google.firebase.FirebaseOptions
|
||||
import com.google.firebase.auth.FirebaseAuth
|
||||
import com.google.firebase.auth.FirebaseCredential
|
||||
import com.google.firebase.auth.FirebaseCredentials
|
||||
import com.google.firebase.auth.UserRecord
|
||||
import com.google.firebase.internal.NonNull
|
||||
import com.google.firebase.tasks.OnFailureListener
|
||||
import com.google.firebase.tasks.OnSuccessListener
|
||||
import io.kamax.matrix.ThreePidMedium
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping
|
||||
import io.kamax.mxisd.lookup.provider.IThreePidProvider
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.function.Consumer
|
||||
import java.util.regex.Pattern
|
||||
|
||||
public class GoogleFirebaseProvider implements IThreePidProvider {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(GoogleFirebaseProvider.class);
|
||||
|
||||
private static final Pattern matrixIdLaxPattern = Pattern.compile("@(.*):(.+)");
|
||||
|
||||
private boolean isEnabled;
|
||||
private String domain;
|
||||
private FirebaseApp fbApp;
|
||||
private FirebaseAuth fbAuth;
|
||||
|
||||
public GoogleFirebaseProvider(boolean isEnabled) {
|
||||
this.isEnabled = isEnabled;
|
||||
}
|
||||
|
||||
public GoogleFirebaseProvider(String credsPath, String db, String domain) {
|
||||
this(true);
|
||||
this.domain = domain;
|
||||
try {
|
||||
fbApp = FirebaseApp.initializeApp(getOpts(credsPath, db), "ThreePidProvider");
|
||||
fbAuth = FirebaseAuth.getInstance(fbApp);
|
||||
|
||||
log.info("Google Firebase Authentication is ready");
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException("Error when initializing Firebase", e);
|
||||
}
|
||||
}
|
||||
|
||||
private FirebaseCredential getCreds(String credsPath) throws IOException {
|
||||
if (StringUtils.isNotBlank(credsPath)) {
|
||||
return FirebaseCredentials.fromCertificate(new FileInputStream(credsPath));
|
||||
} else {
|
||||
return FirebaseCredentials.applicationDefault();
|
||||
}
|
||||
}
|
||||
|
||||
private FirebaseOptions getOpts(String credsPath, String db) throws IOException {
|
||||
if (StringUtils.isBlank(db)) {
|
||||
throw new IllegalArgumentException("Firebase database is not configured");
|
||||
}
|
||||
|
||||
return new FirebaseOptions.Builder()
|
||||
.setCredential(getCreds(credsPath))
|
||||
.setDatabaseUrl(db)
|
||||
.build();
|
||||
}
|
||||
|
||||
private String getMxid(UserRecord record) {
|
||||
return "@${record.getUid()}:${domain}";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return isEnabled;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLocal() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority() {
|
||||
return 25;
|
||||
}
|
||||
|
||||
private void waitOnLatch(CountDownLatch l) {
|
||||
try {
|
||||
l.await(30, TimeUnit.SECONDS);
|
||||
} catch (InterruptedException e) {
|
||||
log.warn("Interrupted while waiting for Firebase auth check");
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<UserRecord> findInternal(String medium, String address) {
|
||||
UserRecord r;
|
||||
CountDownLatch l = new CountDownLatch(1);
|
||||
|
||||
OnSuccessListener<UserRecord> success = new OnSuccessListener<UserRecord>() {
|
||||
@Override
|
||||
void onSuccess(UserRecord result) {
|
||||
log.info("Found 3PID match for {}:{} - UID is {}", medium, address, result.getUid())
|
||||
r = result;
|
||||
l.countDown()
|
||||
}
|
||||
};
|
||||
|
||||
OnFailureListener failure = new OnFailureListener() {
|
||||
@Override
|
||||
void onFailure(@NonNull Exception e) {
|
||||
log.info("No 3PID match for {}:{} - {}", medium, address, e.getMessage())
|
||||
r = null;
|
||||
l.countDown()
|
||||
}
|
||||
};
|
||||
|
||||
if (ThreePidMedium.Email.is(medium)) {
|
||||
log.info("Performing E-mail 3PID lookup for {}", address)
|
||||
fbAuth.getUserByEmail(address)
|
||||
.addOnSuccessListener(success)
|
||||
.addOnFailureListener(failure);
|
||||
waitOnLatch(l);
|
||||
} else if (ThreePidMedium.PhoneNumber.is(medium)) {
|
||||
log.info("Performing msisdn 3PID lookup for {}", address)
|
||||
fbAuth.getUserByPhoneNumber(address)
|
||||
.addOnSuccessListener(success)
|
||||
.addOnFailureListener(failure);
|
||||
waitOnLatch(l);
|
||||
} else {
|
||||
log.info("{} is not a supported 3PID medium", medium);
|
||||
r = null;
|
||||
}
|
||||
|
||||
return Optional.ofNullable(r);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
|
||||
Optional<UserRecord> urOpt = findInternal(request.getType(), request.getThreePid())
|
||||
if (urOpt.isPresent()) {
|
||||
return Optional.of(new SingleLookupReply(request, getMxid(urOpt.get())));
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ThreePidMapping> populate(List<ThreePidMapping> mappings) {
|
||||
List<ThreePidMapping> results = new ArrayList<>();
|
||||
mappings.parallelStream().forEach(new Consumer<ThreePidMapping>() {
|
||||
@Override
|
||||
void accept(ThreePidMapping o) {
|
||||
Optional<UserRecord> urOpt = findInternal(o.getMedium(), o.getValue());
|
||||
if (urOpt.isPresent()) {
|
||||
ThreePidMapping result = new ThreePidMapping();
|
||||
result.setMedium(o.getMedium())
|
||||
result.setValue(o.getValue())
|
||||
result.setMxid(getMxid(urOpt.get()))
|
||||
results.add(result)
|
||||
}
|
||||
}
|
||||
});
|
||||
return results;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.ldap;
|
||||
|
||||
import io.kamax.matrix._MatrixID;
|
||||
import io.kamax.mxisd.UserIdType;
|
||||
import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
|
||||
import io.kamax.mxisd.auth.provider.BackendAuthResult;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.directory.api.ldap.model.cursor.CursorException;
|
||||
import org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException;
|
||||
import org.apache.directory.api.ldap.model.cursor.EntryCursor;
|
||||
import org.apache.directory.api.ldap.model.entry.Attribute;
|
||||
import org.apache.directory.api.ldap.model.entry.Entry;
|
||||
import org.apache.directory.api.ldap.model.exception.LdapException;
|
||||
import org.apache.directory.api.ldap.model.message.SearchScope;
|
||||
import org.apache.directory.ldap.client.api.LdapConnection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class LdapAuthProvider extends LdapGenericBackend implements AuthenticatorProvider {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(LdapAuthProvider.class);
|
||||
|
||||
private String getUidAttribute() {
|
||||
return getCfg().getAttribute().getUid().getValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return getCfg().isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
|
||||
log.info("Performing auth for {}", mxid);
|
||||
|
||||
LdapConnection conn = getConn();
|
||||
try {
|
||||
bind(conn);
|
||||
|
||||
String uidType = getCfg().getAttribute().getUid().getType();
|
||||
String userFilterValue = StringUtils.equals(LdapThreePidProvider.UID, uidType) ? mxid.getLocalPart() : mxid.getId();
|
||||
if (StringUtils.isBlank(userFilterValue)) {
|
||||
log.warn("Username is empty, failing auth");
|
||||
return BackendAuthResult.failure();
|
||||
}
|
||||
|
||||
String userFilter = "(" + getCfg().getAttribute().getUid().getValue() + "=" + userFilterValue + ")";
|
||||
if (!StringUtils.isBlank(getCfg().getAuth().getFilter())) {
|
||||
userFilter = "(&" + getCfg().getAuth().getFilter() + userFilter + ")";
|
||||
}
|
||||
EntryCursor cursor = conn.search(getCfg().getConn().getBaseDn(), userFilter, SearchScope.SUBTREE, getUidAttribute(), getCfg().getAttribute().getName());
|
||||
try {
|
||||
while (cursor.next()) {
|
||||
Entry entry = cursor.get();
|
||||
String dn = entry.getDn().getName();
|
||||
log.info("Checking possible match, DN: {}", dn);
|
||||
|
||||
Attribute attribute = entry.get(getUidAttribute());
|
||||
if (attribute == null) {
|
||||
log.info("DN {}: no attribute {}, skpping", dn, getUidAttribute());
|
||||
continue;
|
||||
}
|
||||
|
||||
String data = attribute.get().toString();
|
||||
if (data.length() < 1) {
|
||||
log.info("DN {}: empty attribute {}, skipping", getUidAttribute());
|
||||
continue;
|
||||
}
|
||||
|
||||
log.info("Attempting authentication on LDAP for {}", dn);
|
||||
try {
|
||||
conn.bind(entry.getDn(), password);
|
||||
} catch (LdapException e) {
|
||||
log.info("Unable to bind using {} because {}", entry.getDn().getName(), e.getMessage());
|
||||
return BackendAuthResult.failure();
|
||||
}
|
||||
|
||||
Attribute nameAttribute = entry.get(getCfg().getAttribute().getName());
|
||||
String name = nameAttribute != null ? nameAttribute.get().toString() : null;
|
||||
|
||||
log.info("Authentication successful for {}", entry.getDn().getName());
|
||||
log.info("DN {} is a valid match", dn);
|
||||
|
||||
// TODO should we canonicalize the MXID?
|
||||
return BackendAuthResult.success(mxid.getId(), UserIdType.MatrixID, name);
|
||||
}
|
||||
} catch (CursorLdapReferralException e) {
|
||||
log.warn("Entity for {} is only available via referral, skipping", mxid);
|
||||
} finally {
|
||||
cursor.close();
|
||||
}
|
||||
|
||||
log.info("No match were found for {}", mxid);
|
||||
return BackendAuthResult.failure();
|
||||
} catch (LdapException | IOException | CursorException e) {
|
||||
throw new RuntimeException(e);
|
||||
} finally {
|
||||
try {
|
||||
conn.close();
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.ldap;
|
||||
|
||||
import io.kamax.mxisd.config.ldap.LdapConfig;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.directory.api.ldap.model.exception.LdapException;
|
||||
import org.apache.directory.ldap.client.api.LdapConnection;
|
||||
import org.apache.directory.ldap.client.api.LdapNetworkConnection;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class LdapGenericBackend {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(LdapGenericBackend.class);
|
||||
|
||||
@Autowired
|
||||
private LdapConfig ldapCfg;
|
||||
|
||||
protected LdapConnection getConn() {
|
||||
return new LdapNetworkConnection(ldapCfg.getConn().getHost(), ldapCfg.getConn().getPort(), ldapCfg.getConn().isTls());
|
||||
}
|
||||
|
||||
protected void bind(LdapConnection conn) throws LdapException {
|
||||
if (StringUtils.isBlank(ldapCfg.getConn().getBindDn()) && StringUtils.isBlank(ldapCfg.getConn().getBindPassword())) {
|
||||
conn.anonymousBind();
|
||||
} else {
|
||||
conn.bind(ldapCfg.getConn().getBindDn(), ldapCfg.getConn().getBindPassword());
|
||||
}
|
||||
}
|
||||
|
||||
protected LdapConfig getCfg() {
|
||||
return ldapCfg;
|
||||
}
|
||||
|
||||
}
|
@@ -18,12 +18,13 @@
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.lookup.provider
|
||||
package io.kamax.mxisd.backend.ldap
|
||||
|
||||
import io.kamax.mxisd.config.LdapConfig
|
||||
import io.kamax.mxisd.config.ServerConfig
|
||||
import io.kamax.mxisd.config.MatrixConfig
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping
|
||||
import io.kamax.mxisd.lookup.provider.IThreePidProvider
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException
|
||||
import org.apache.directory.api.ldap.model.cursor.EntryCursor
|
||||
@@ -31,29 +32,29 @@ import org.apache.directory.api.ldap.model.entry.Attribute
|
||||
import org.apache.directory.api.ldap.model.entry.Entry
|
||||
import org.apache.directory.api.ldap.model.message.SearchScope
|
||||
import org.apache.directory.ldap.client.api.LdapConnection
|
||||
import org.apache.directory.ldap.client.api.LdapNetworkConnection
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.stereotype.Component
|
||||
|
||||
@Component
|
||||
class LdapProvider implements IThreePidProvider {
|
||||
class LdapThreePidProvider extends LdapGenericBackend implements IThreePidProvider {
|
||||
|
||||
public static final String UID = "uid"
|
||||
public static final String MATRIX_ID = "mxid"
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(LdapProvider.class)
|
||||
private Logger log = LoggerFactory.getLogger(LdapThreePidProvider.class)
|
||||
|
||||
@Autowired
|
||||
private ServerConfig srvCfg
|
||||
|
||||
@Autowired
|
||||
private LdapConfig ldapCfg
|
||||
private MatrixConfig mxCfg
|
||||
|
||||
@Override
|
||||
boolean isEnabled() {
|
||||
return ldapCfg.getEnabled()
|
||||
return getCfg().isEnabled()
|
||||
}
|
||||
|
||||
private String getUidAttribute() {
|
||||
return getCfg().getAttribute().getUid().getValue();
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -67,39 +68,42 @@ class LdapProvider implements IThreePidProvider {
|
||||
}
|
||||
|
||||
Optional<String> lookup(LdapConnection conn, String medium, String value) {
|
||||
Optional<String> queryOpt = ldapCfg.getMapping(medium)
|
||||
String uidAttribute = getUidAttribute()
|
||||
|
||||
Optional<String> queryOpt = getCfg().getIdentity().getQuery(medium)
|
||||
if (!queryOpt.isPresent()) {
|
||||
log.warn("{} is not a configured 3PID type for LDAP lookup", medium)
|
||||
return Optional.empty()
|
||||
}
|
||||
|
||||
String searchQuery = queryOpt.get().replaceAll("%3pid", value)
|
||||
EntryCursor cursor = conn.search(ldapCfg.getBaseDn(), searchQuery, SearchScope.SUBTREE, ldapCfg.getAttribute())
|
||||
EntryCursor cursor = conn.search(getCfg().getConn().getBaseDn(), searchQuery, SearchScope.SUBTREE, uidAttribute)
|
||||
try {
|
||||
while (cursor.next()) {
|
||||
Entry entry = cursor.get()
|
||||
log.info("Found possible match, DN: {}", entry.getDn().getName())
|
||||
|
||||
Attribute attribute = entry.get(ldapCfg.getAttribute())
|
||||
Attribute attribute = entry.get(uidAttribute)
|
||||
if (attribute == null) {
|
||||
log.info("DN {}: no attribute {}, skpping", entry.getDn(), ldapCfg.getAttribute())
|
||||
log.info("DN {}: no attribute {}, skpping", entry.getDn(), getCfg().getAttribute())
|
||||
continue
|
||||
}
|
||||
|
||||
String data = attribute.get().toString()
|
||||
if (data.length() < 1) {
|
||||
log.info("DN {}: empty attribute {}, skipping", ldapCfg.getAttribute())
|
||||
log.info("DN {}: empty attribute {}, skipping", getCfg().getAttribute())
|
||||
continue
|
||||
}
|
||||
|
||||
StringBuilder matrixId = new StringBuilder()
|
||||
// TODO Should we turn this block into a map of functions?
|
||||
if (StringUtils.equals(UID, ldapCfg.getType())) {
|
||||
matrixId.append("@").append(data).append(":").append(srvCfg.getName())
|
||||
} else if (StringUtils.equals(MATRIX_ID, ldapCfg.getType())) {
|
||||
String uidType = getCfg().getAttribute().getUid().getType()
|
||||
if (StringUtils.equals(UID, uidType)) {
|
||||
matrixId.append("@").append(data).append(":").append(mxCfg.getDomain())
|
||||
} else if (StringUtils.equals(MATRIX_ID, uidType)) {
|
||||
matrixId.append(data)
|
||||
} else {
|
||||
log.warn("Bind was found but type {} is not supported", ldapCfg.getType())
|
||||
log.warn("Bind was found but type {} is not supported", uidType)
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -116,23 +120,16 @@ class LdapProvider implements IThreePidProvider {
|
||||
}
|
||||
|
||||
@Override
|
||||
Optional<?> find(SingleLookupRequest request) {
|
||||
Optional<SingleLookupReply> find(SingleLookupRequest request) {
|
||||
log.info("Performing LDAP lookup ${request.getThreePid()} of type ${request.getType()}")
|
||||
|
||||
LdapConnection conn = new LdapNetworkConnection(ldapCfg.getHost(), ldapCfg.getPort(), ldapCfg.getTls())
|
||||
LdapConnection conn = getConn()
|
||||
try {
|
||||
conn.bind(ldapCfg.getBindDn(), ldapCfg.getBindPassword())
|
||||
bind(conn)
|
||||
|
||||
Optional<String> mxid = lookup(conn, request.getType(), request.getThreePid())
|
||||
if (mxid.isPresent()) {
|
||||
return Optional.of([
|
||||
address : request.getThreePid(),
|
||||
medium : request.getType(),
|
||||
mxid : mxid.get(),
|
||||
not_before: 0,
|
||||
not_after : 9223372036854775807,
|
||||
ts : 0
|
||||
])
|
||||
return Optional.of(new SingleLookupReply(request, mxid.get()));
|
||||
}
|
||||
} finally {
|
||||
conn.close()
|
||||
@@ -147,9 +144,9 @@ class LdapProvider implements IThreePidProvider {
|
||||
log.info("Looking up {} mappings", mappings.size())
|
||||
List<ThreePidMapping> mappingsFound = new ArrayList<>()
|
||||
|
||||
LdapConnection conn = new LdapNetworkConnection(ldapCfg.getHost(), ldapCfg.getPort())
|
||||
LdapConnection conn = getConn()
|
||||
try {
|
||||
conn.bind(ldapCfg.getBindDn(), ldapCfg.getBindPassword())
|
||||
bind(conn)
|
||||
|
||||
for (ThreePidMapping mapping : mappings) {
|
||||
try {
|
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public class LookupBulkResponseJson {
|
||||
|
||||
private List<LookupSingleResponseJson> lookup = new ArrayList<>();
|
||||
|
||||
public List<LookupSingleResponseJson> getLookup() {
|
||||
return lookup;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
public class LookupSingleRequestJson {
|
||||
|
||||
private String medium;
|
||||
private String address;
|
||||
|
||||
public LookupSingleRequestJson(String medium, String address) {
|
||||
this.medium = medium;
|
||||
this.address = address;
|
||||
}
|
||||
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
}
|
@@ -0,0 +1,43 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
import io.kamax.mxisd.UserID;
|
||||
|
||||
public class LookupSingleResponseJson {
|
||||
|
||||
private String medium;
|
||||
private String address;
|
||||
private UserID id;
|
||||
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public UserID getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
import io.kamax.matrix._MatrixID;
|
||||
import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
|
||||
import io.kamax.mxisd.auth.provider.BackendAuthResult;
|
||||
import io.kamax.mxisd.config.rest.RestBackendConfig;
|
||||
import io.kamax.mxisd.util.RestClientUtils;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
@Component
|
||||
public class RestAuthProvider extends RestProvider implements AuthenticatorProvider {
|
||||
|
||||
@Autowired
|
||||
public RestAuthProvider(RestBackendConfig cfg) {
|
||||
super(cfg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return cfg.isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
|
||||
RestAuthRequestJson auth = new RestAuthRequestJson();
|
||||
auth.setMxid(mxid.getId());
|
||||
auth.setLocalpart(mxid.getLocalPart());
|
||||
auth.setDomain(mxid.getDomain());
|
||||
auth.setPassword(password);
|
||||
|
||||
HttpUriRequest req = RestClientUtils.post(cfg.getEndpoints().getAuth(), gson, "auth", auth);
|
||||
try (CloseableHttpResponse res = client.execute(req)) {
|
||||
int status = res.getStatusLine().getStatusCode();
|
||||
if (status < 200 || status >= 300) {
|
||||
return BackendAuthResult.failure();
|
||||
}
|
||||
|
||||
return parser.parse(res, "auth", BackendAuthResult.class);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
public class RestAuthRequestJson {
|
||||
|
||||
private String mxid;
|
||||
private String localpart;
|
||||
private String domain;
|
||||
private String password;
|
||||
|
||||
public String getMxid() {
|
||||
return mxid;
|
||||
}
|
||||
|
||||
public void setMxid(String mxid) {
|
||||
this.mxid = mxid;
|
||||
}
|
||||
|
||||
public String getLocalpart() {
|
||||
return localpart;
|
||||
}
|
||||
|
||||
public void setLocalpart(String localpart) {
|
||||
this.localpart = localpart;
|
||||
}
|
||||
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
public void setDomain(String domain) {
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
import com.google.gson.FieldNamingPolicy;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import io.kamax.mxisd.config.rest.RestBackendConfig;
|
||||
import io.kamax.mxisd.util.GsonParser;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
|
||||
public class RestProvider {
|
||||
|
||||
protected RestBackendConfig cfg;
|
||||
protected Gson gson;
|
||||
protected GsonParser parser;
|
||||
protected CloseableHttpClient client;
|
||||
|
||||
public RestProvider(RestBackendConfig cfg) {
|
||||
this.cfg = cfg;
|
||||
|
||||
client = HttpClients.createDefault();
|
||||
gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
|
||||
parser = new GsonParser(gson);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.rest;
|
||||
|
||||
import io.kamax.matrix.MatrixID;
|
||||
import io.kamax.matrix._MatrixID;
|
||||
import io.kamax.mxisd.UserID;
|
||||
import io.kamax.mxisd.UserIdType;
|
||||
import io.kamax.mxisd.config.MatrixConfig;
|
||||
import io.kamax.mxisd.config.rest.RestBackendConfig;
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply;
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest;
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping;
|
||||
import io.kamax.mxisd.lookup.provider.IThreePidProvider;
|
||||
import io.kamax.mxisd.util.RestClientUtils;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpUriRequest;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Component
|
||||
public class RestThreePidProvider extends RestProvider implements IThreePidProvider {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(RestThreePidProvider.class);
|
||||
|
||||
private MatrixConfig mxCfg; // FIXME should be done in the lookup manager
|
||||
|
||||
@Autowired
|
||||
public RestThreePidProvider(RestBackendConfig cfg, MatrixConfig mxCfg) {
|
||||
super(cfg);
|
||||
this.mxCfg = mxCfg;
|
||||
}
|
||||
|
||||
// TODO refactor in lookup manager with above FIXME
|
||||
private _MatrixID getMxId(UserID id) {
|
||||
if (UserIdType.Localpart.is(id.getType())) {
|
||||
return new MatrixID(id.getValue(), mxCfg.getDomain());
|
||||
} else {
|
||||
return new MatrixID(id.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return cfg.isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLocal() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority() {
|
||||
return 20;
|
||||
}
|
||||
|
||||
// TODO refactor common code
|
||||
@Override
|
||||
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
|
||||
String endpoint = cfg.getEndpoints().getIdentity().getSingle();
|
||||
HttpUriRequest req = RestClientUtils.post(endpoint, gson, "lookup",
|
||||
new LookupSingleRequestJson(request.getType(), request.getThreePid()));
|
||||
|
||||
try (CloseableHttpResponse res = client.execute(req)) {
|
||||
int status = res.getStatusLine().getStatusCode();
|
||||
if (status < 200 || status >= 300) {
|
||||
log.warn("REST endpoint {} answered with status {}, no binding found", endpoint, status);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
Optional<LookupSingleResponseJson> responseOpt = parser.parseOptional(res, "lookup", LookupSingleResponseJson.class);
|
||||
return responseOpt.map(lookupSingleResponseJson -> new SingleLookupReply(request, getMxId(lookupSingleResponseJson.getId())));
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
// TODO refactor common code
|
||||
@Override
|
||||
public List<ThreePidMapping> populate(List<ThreePidMapping> mappings) {
|
||||
List<LookupSingleRequestJson> ioListRequest = mappings.stream()
|
||||
.map(mapping -> new LookupSingleRequestJson(mapping.getMedium(), mapping.getValue()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
HttpUriRequest req = RestClientUtils.post(
|
||||
cfg.getEndpoints().getIdentity().getBulk(), gson, "lookup", ioListRequest);
|
||||
try (CloseableHttpResponse res = client.execute(req)) {
|
||||
mappings = new ArrayList<>();
|
||||
|
||||
int status = res.getStatusLine().getStatusCode();
|
||||
if (status < 200 || status >= 300) {
|
||||
return mappings;
|
||||
}
|
||||
|
||||
LookupBulkResponseJson listIo = parser.parse(res, LookupBulkResponseJson.class);
|
||||
return listIo.getLookup().stream()
|
||||
.map(io -> new ThreePidMapping(io.getMedium(), io.getAddress(), getMxId(io.getId()).getId()))
|
||||
.collect(Collectors.toList());
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.sql;
|
||||
|
||||
import io.kamax.matrix._MatrixID;
|
||||
import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
|
||||
import io.kamax.mxisd.auth.provider.BackendAuthResult;
|
||||
import io.kamax.mxisd.config.ServerConfig;
|
||||
import io.kamax.mxisd.config.sql.SqlProviderConfig;
|
||||
import io.kamax.mxisd.invitation.InvitationManager;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class SqlAuthProvider implements AuthenticatorProvider {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(SqlAuthProvider.class);
|
||||
|
||||
@Autowired
|
||||
private ServerConfig srvCfg;
|
||||
|
||||
@Autowired
|
||||
private SqlProviderConfig cfg;
|
||||
|
||||
@Autowired
|
||||
private InvitationManager invMgr;
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return cfg.isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
|
||||
log.info("Performing dummy authentication try to force invite mapping refresh");
|
||||
|
||||
invMgr.lookupMappingsForInvites();
|
||||
return BackendAuthResult.failure();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.backend.sql;
|
||||
|
||||
import io.kamax.matrix.MatrixID;
|
||||
import io.kamax.mxisd.config.MatrixConfig;
|
||||
import io.kamax.mxisd.config.sql.SqlProviderConfig;
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply;
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest;
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping;
|
||||
import io.kamax.mxisd.lookup.provider.IThreePidProvider;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.sql.*;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Component
|
||||
public class SqlThreePidProvider implements IThreePidProvider {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(SqlThreePidProvider.class);
|
||||
|
||||
@Autowired
|
||||
private MatrixConfig mxCfg;
|
||||
|
||||
@Autowired
|
||||
private SqlProviderConfig cfg;
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return cfg.isEnabled();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isLocal() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getPriority() {
|
||||
return 20;
|
||||
}
|
||||
|
||||
private Connection getConn() throws SQLException {
|
||||
return DriverManager.getConnection("jdbc:" + cfg.getType() + ":" + cfg.getConnection());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
|
||||
log.info("SQL lookup");
|
||||
String stmtSql = StringUtils.defaultIfBlank(cfg.getIdentity().getMedium().get(request.getType()), cfg.getIdentity().getQuery());
|
||||
log.info("SQL query: {}", stmtSql);
|
||||
try (PreparedStatement stmt = getConn().prepareStatement(stmtSql)) {
|
||||
stmt.setString(1, request.getType().toLowerCase());
|
||||
stmt.setString(2, request.getThreePid().toLowerCase());
|
||||
|
||||
ResultSet rSet = stmt.executeQuery();
|
||||
while (rSet.next()) {
|
||||
String uid = rSet.getString("uid");
|
||||
log.info("Found match: {}", uid);
|
||||
if (StringUtils.equals("uid", cfg.getIdentity().getType())) {
|
||||
log.info("Resolving as localpart");
|
||||
return Optional.of(new SingleLookupReply(request, new MatrixID(uid, mxCfg.getDomain())));
|
||||
}
|
||||
if (StringUtils.equals("mxid", cfg.getIdentity().getType())) {
|
||||
log.info("Resolving as MXID");
|
||||
return Optional.of(new SingleLookupReply(request, new MatrixID(uid)));
|
||||
}
|
||||
|
||||
log.info("Identity type is unknown, skipping");
|
||||
}
|
||||
|
||||
log.info("No match found in SQL");
|
||||
return Optional.empty();
|
||||
} catch (SQLException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<ThreePidMapping> populate(List<ThreePidMapping> mappings) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
}
|
52
src/main/groovy/io/kamax/mxisd/config/DnsOverwrite.java
Normal file
52
src/main/groovy/io/kamax/mxisd/config/DnsOverwrite.java
Normal file
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("dns.overwrite")
|
||||
public class DnsOverwrite {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(DnsOverwrite.class);
|
||||
|
||||
@Autowired
|
||||
private ServerConfig srvCfg;
|
||||
|
||||
@Autowired
|
||||
private DnsOverwriteEntry homeserver;
|
||||
|
||||
public Optional<DnsOverwriteEntry> findHost(String lookup) {
|
||||
if (homeserver != null && StringUtils.equalsIgnoreCase(lookup, homeserver.getName())) {
|
||||
return Optional.of(homeserver);
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
}
|
67
src/main/groovy/io/kamax/mxisd/config/DnsOverwriteEntry.java
Normal file
67
src/main/groovy/io/kamax/mxisd/config/DnsOverwriteEntry.java
Normal file
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("dns.overwrite.homeserver")
|
||||
public class DnsOverwriteEntry {
|
||||
|
||||
private String name;
|
||||
private String type;
|
||||
private String value;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public String getTarget() {
|
||||
if (StringUtils.equals("env", getType())) {
|
||||
return System.getenv(getValue());
|
||||
} else {
|
||||
return getValue();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
101
src/main/groovy/io/kamax/mxisd/config/FirebaseConfig.java
Normal file
101
src/main/groovy/io/kamax/mxisd/config/FirebaseConfig.java
Normal file
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
|
||||
import io.kamax.mxisd.backend.firebase.GoogleFirebaseAuthenticator;
|
||||
import io.kamax.mxisd.backend.firebase.GoogleFirebaseProvider;
|
||||
import io.kamax.mxisd.lookup.provider.IThreePidProvider;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("firebase")
|
||||
public class FirebaseConfig {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(FirebaseConfig.class);
|
||||
|
||||
@Autowired
|
||||
private MatrixConfig mxCfg;
|
||||
|
||||
private boolean enabled;
|
||||
private String credentials;
|
||||
private String database;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getCredentials() {
|
||||
return credentials;
|
||||
}
|
||||
|
||||
public void setCredentials(String credentials) {
|
||||
this.credentials = credentials;
|
||||
}
|
||||
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
|
||||
public void setDatabase(String database) {
|
||||
this.database = database;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void postConstruct() {
|
||||
log.info("--- Firebase configuration ---");
|
||||
log.info("Enabled: {}", isEnabled());
|
||||
if (isEnabled()) {
|
||||
log.info("Credentials: {}", getCredentials());
|
||||
log.info("Database: {}", getDatabase());
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public AuthenticatorProvider getAuthProvider() {
|
||||
if (!enabled) {
|
||||
return new GoogleFirebaseAuthenticator(false);
|
||||
} else {
|
||||
return new GoogleFirebaseAuthenticator(credentials, database, mxCfg.getDomain());
|
||||
}
|
||||
}
|
||||
|
||||
@Bean
|
||||
public IThreePidProvider getLookupProvider() {
|
||||
if (!enabled) {
|
||||
return new GoogleFirebaseProvider(false);
|
||||
} else {
|
||||
return new GoogleFirebaseProvider(credentials, database, mxCfg.getDomain());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -27,7 +27,7 @@ import org.springframework.context.annotation.Configuration
|
||||
@ConfigurationProperties(prefix = "forward")
|
||||
class ForwardConfig {
|
||||
|
||||
private List<String> servers
|
||||
private List<String> servers = new ArrayList<>()
|
||||
|
||||
List<String> getServers() {
|
||||
return servers
|
||||
|
@@ -20,6 +20,7 @@
|
||||
|
||||
package io.kamax.mxisd.config
|
||||
|
||||
import io.kamax.mxisd.exception.ConfigurationException
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.springframework.beans.factory.InitializingBean
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties
|
||||
@@ -42,7 +43,7 @@ class KeyConfig implements InitializingBean {
|
||||
@Override
|
||||
void afterPropertiesSet() throws Exception {
|
||||
if (StringUtils.isBlank(getPath())) {
|
||||
throw new RuntimeException("Key path must be configured!")
|
||||
throw new ConfigurationException("key.path")
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,156 +0,0 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config
|
||||
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.InitializingBean
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap")
|
||||
class LdapConfig implements InitializingBean {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(LdapConfig.class)
|
||||
|
||||
private boolean enabled
|
||||
private boolean tls
|
||||
private String host
|
||||
private int port
|
||||
private String baseDn
|
||||
private String type
|
||||
private String attribute
|
||||
private String bindDn
|
||||
private String bindPassword
|
||||
private Map<String, String> mappings
|
||||
|
||||
boolean getEnabled() {
|
||||
return enabled
|
||||
}
|
||||
|
||||
void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled
|
||||
}
|
||||
|
||||
boolean getTls() {
|
||||
return tls
|
||||
}
|
||||
|
||||
void setTls(boolean tls) {
|
||||
this.tls = tls
|
||||
}
|
||||
|
||||
String getHost() {
|
||||
return host
|
||||
}
|
||||
|
||||
void setHost(String host) {
|
||||
this.host = host
|
||||
}
|
||||
|
||||
int getPort() {
|
||||
return port
|
||||
}
|
||||
|
||||
void setPort(int port) {
|
||||
this.port = port
|
||||
}
|
||||
|
||||
String getBaseDn() {
|
||||
return baseDn
|
||||
}
|
||||
|
||||
void setBaseDn(String baseDn) {
|
||||
this.baseDn = baseDn
|
||||
}
|
||||
|
||||
String getType() {
|
||||
return type
|
||||
}
|
||||
|
||||
void setType(String type) {
|
||||
this.type = type
|
||||
}
|
||||
|
||||
String getAttribute() {
|
||||
return attribute
|
||||
}
|
||||
|
||||
void setAttribute(String attribute) {
|
||||
this.attribute = attribute
|
||||
}
|
||||
|
||||
String getBindDn() {
|
||||
return bindDn
|
||||
}
|
||||
|
||||
void setBindDn(String bindDn) {
|
||||
this.bindDn = bindDn
|
||||
}
|
||||
|
||||
String getBindPassword() {
|
||||
return bindPassword
|
||||
}
|
||||
|
||||
void setBindPassword(String bindPassword) {
|
||||
this.bindPassword = bindPassword
|
||||
}
|
||||
|
||||
Map<String, String> getMappings() {
|
||||
return mappings
|
||||
}
|
||||
|
||||
void setMappings(Map<String, String> mappings) {
|
||||
this.mappings = mappings
|
||||
}
|
||||
|
||||
Optional<String> getMapping(String type) {
|
||||
if (mappings == null) {
|
||||
return Optional.empty()
|
||||
}
|
||||
|
||||
return Optional.ofNullable(mappings.get(type))
|
||||
}
|
||||
|
||||
@Override
|
||||
void afterPropertiesSet() throws Exception {
|
||||
log.info("LDAP enabled: {}", getEnabled())
|
||||
|
||||
if (!getEnabled()) {
|
||||
return
|
||||
}
|
||||
|
||||
log.info("Matrix ID type: {}", getType())
|
||||
log.info("LDAP Host: {}", getHost())
|
||||
log.info("LDAP Bind DN: {}", getBindDn())
|
||||
log.info("LDAP Attribute: {}", getAttribute())
|
||||
|
||||
if (StringUtils.isBlank(getHost())) {
|
||||
throw new IllegalStateException("LDAP Host must be configured!")
|
||||
}
|
||||
if (StringUtils.isBlank(getAttribute())) {
|
||||
throw new IllegalStateException("LDAP attribute must be configured!")
|
||||
}
|
||||
}
|
||||
|
||||
}
|
94
src/main/groovy/io/kamax/mxisd/config/MatrixConfig.java
Normal file
94
src/main/groovy/io/kamax/mxisd/config/MatrixConfig.java
Normal file
@@ -0,0 +1,94 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import io.kamax.mxisd.exception.ConfigurationException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("matrix")
|
||||
public class MatrixConfig {
|
||||
|
||||
public static class Identity {
|
||||
private Map<String, List<String>> servers = new HashMap<>();
|
||||
|
||||
public Map<String, List<String>> getServers() {
|
||||
return servers;
|
||||
}
|
||||
|
||||
public void setServers(Map<String, List<String>> servers) {
|
||||
this.servers = servers;
|
||||
}
|
||||
|
||||
public List<String> getServers(String label) {
|
||||
if (!servers.containsKey(label)) {
|
||||
throw new RuntimeException("No Identity server list with label '" + label + "'");
|
||||
}
|
||||
|
||||
return servers.get(label);
|
||||
}
|
||||
}
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(MatrixConfig.class);
|
||||
|
||||
private String domain;
|
||||
private Identity identity = new Identity();
|
||||
|
||||
public String getDomain() {
|
||||
return domain;
|
||||
}
|
||||
|
||||
public void setDomain(String domain) {
|
||||
this.domain = domain;
|
||||
}
|
||||
|
||||
public Identity getIdentity() {
|
||||
return identity;
|
||||
}
|
||||
|
||||
public void setIdentity(Identity identity) {
|
||||
this.identity = identity;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- Matrix config ---");
|
||||
|
||||
if (StringUtils.isBlank(domain)) {
|
||||
throw new ConfigurationException("matrix.domain");
|
||||
}
|
||||
|
||||
log.info("Domain: {}", getDomain());
|
||||
log.info("Identity:");
|
||||
log.info("\tServers: {}", new Gson().toJson(identity.getServers()));
|
||||
}
|
||||
|
||||
}
|
@@ -1,3 +1,23 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config
|
||||
|
||||
import org.slf4j.Logger
|
||||
@@ -15,7 +35,7 @@ class RecursiveLookupBridgeConfig implements InitializingBean {
|
||||
private boolean enabled
|
||||
private boolean recursiveOnly
|
||||
private String server
|
||||
private Map<String, String> mappings
|
||||
private Map<String, String> mappings = new HashMap<>()
|
||||
|
||||
boolean getEnabled() {
|
||||
return enabled
|
||||
@@ -51,10 +71,13 @@ class RecursiveLookupBridgeConfig implements InitializingBean {
|
||||
|
||||
@Override
|
||||
void afterPropertiesSet() throws Exception {
|
||||
log.info("--- Bridge integration lookups config ---")
|
||||
log.info("Enabled: {}", getEnabled())
|
||||
if (getEnabled()) {
|
||||
log.info("Recursive only: {}", getRecursiveOnly())
|
||||
log.info("Server: {}", getServer())
|
||||
log.info("Fallback Server: {}", getServer())
|
||||
log.info("Mappings: {}", mappings.size())
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("storage.provider.sqlite")
|
||||
public class SQLiteStorageConfig {
|
||||
|
||||
private String database;
|
||||
|
||||
public String getDatabase() {
|
||||
return database;
|
||||
}
|
||||
|
||||
public void setDatabase(String database) {
|
||||
this.database = database;
|
||||
}
|
||||
|
||||
}
|
@@ -21,7 +21,10 @@
|
||||
package io.kamax.mxisd.config
|
||||
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.InitializingBean
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
@@ -29,7 +32,14 @@ import org.springframework.context.annotation.Configuration
|
||||
@ConfigurationProperties(prefix = "server")
|
||||
class ServerConfig implements InitializingBean {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(ServerConfig.class);
|
||||
|
||||
@Autowired
|
||||
private MatrixConfig mxCfg;
|
||||
|
||||
private String name
|
||||
private int port
|
||||
private String publicUrl
|
||||
|
||||
String getName() {
|
||||
return name
|
||||
@@ -39,11 +49,47 @@ class ServerConfig implements InitializingBean {
|
||||
this.name = name
|
||||
}
|
||||
|
||||
int getPort() {
|
||||
return port
|
||||
}
|
||||
|
||||
void setPort(int port) {
|
||||
this.port = port
|
||||
}
|
||||
|
||||
String getPublicUrl() {
|
||||
return publicUrl
|
||||
}
|
||||
|
||||
void setPublicUrl(String publicUrl) {
|
||||
this.publicUrl = publicUrl
|
||||
}
|
||||
|
||||
@Override
|
||||
void afterPropertiesSet() throws Exception {
|
||||
log.info("--- Server config ---")
|
||||
|
||||
if (StringUtils.isBlank(getName())) {
|
||||
throw new RuntimeException("Server name must be configured. Use the same realm as your Homeserver")
|
||||
setName(mxCfg.getDomain());
|
||||
log.debug("server.name is empty, using matrix.domain");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(getPublicUrl())) {
|
||||
setPublicUrl("https://${getName()}");
|
||||
log.debug("Public URL is empty, generating from name");
|
||||
} else {
|
||||
setPublicUrl(StringUtils.replace(getPublicUrl(), "%SERVER_NAME%", getName()));
|
||||
}
|
||||
|
||||
try {
|
||||
new URL(getPublicUrl())
|
||||
} catch (MalformedURLException e) {
|
||||
log.warn("Public URL is not valid: {}", StringUtils.defaultIfBlank(e.getMessage(), "<no reason provided>"))
|
||||
}
|
||||
|
||||
log.info("Name: {}", getName())
|
||||
log.info("Port: {}", getPort())
|
||||
log.info("Public URL: {}", getPublicUrl())
|
||||
}
|
||||
|
||||
}
|
||||
|
173
src/main/groovy/io/kamax/mxisd/config/SessionConfig.java
Normal file
173
src/main/groovy/io/kamax/mxisd/config/SessionConfig.java
Normal file
@@ -0,0 +1,173 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("session")
|
||||
public class SessionConfig {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(SessionConfig.class);
|
||||
|
||||
public static class Policy {
|
||||
|
||||
public static class PolicyTemplate {
|
||||
|
||||
public static class PolicySource {
|
||||
|
||||
public static class PolicySourceRemote {
|
||||
|
||||
private boolean enabled;
|
||||
private String server;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getServer() {
|
||||
return server;
|
||||
}
|
||||
|
||||
public void setServer(String server) {
|
||||
this.server = server;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean enabled;
|
||||
private boolean toLocal;
|
||||
private PolicySourceRemote toRemote = new PolicySourceRemote();
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public boolean toLocal() {
|
||||
return toLocal;
|
||||
}
|
||||
|
||||
public void setToLocal(boolean toLocal) {
|
||||
this.toLocal = toLocal;
|
||||
}
|
||||
|
||||
public boolean toRemote() {
|
||||
return toRemote.isEnabled();
|
||||
}
|
||||
|
||||
public PolicySourceRemote getToRemote() {
|
||||
return toRemote;
|
||||
}
|
||||
|
||||
public void setToRemote(PolicySourceRemote toRemote) {
|
||||
this.toRemote = toRemote;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private boolean enabled;
|
||||
private PolicySource forLocal = new PolicySource();
|
||||
private PolicySource forRemote = new PolicySource();
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public PolicySource getForLocal() {
|
||||
return forLocal;
|
||||
}
|
||||
|
||||
public PolicySource forLocal() {
|
||||
return forLocal;
|
||||
}
|
||||
|
||||
public PolicySource getForRemote() {
|
||||
return forRemote;
|
||||
}
|
||||
|
||||
public PolicySource forRemote() {
|
||||
return forRemote;
|
||||
}
|
||||
|
||||
public PolicySource forIf(boolean isLocal) {
|
||||
return isLocal ? forLocal : forRemote;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private PolicyTemplate validation = new PolicyTemplate();
|
||||
|
||||
public PolicyTemplate getValidation() {
|
||||
return validation;
|
||||
}
|
||||
|
||||
public void setValidation(PolicyTemplate validation) {
|
||||
this.validation = validation;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private MatrixConfig mxCfg;
|
||||
private Policy policy = new Policy();
|
||||
|
||||
@Autowired
|
||||
public SessionConfig(MatrixConfig mxCfg) {
|
||||
this.mxCfg = mxCfg;
|
||||
}
|
||||
|
||||
public MatrixConfig getMatrixCfg() {
|
||||
return mxCfg;
|
||||
}
|
||||
|
||||
public Policy getPolicy() {
|
||||
return policy;
|
||||
}
|
||||
|
||||
public void setPolicy(Policy policy) {
|
||||
this.policy = policy;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- Session config ---");
|
||||
log.info("Global Policy: {}", new Gson().toJson(policy));
|
||||
}
|
||||
|
||||
}
|
51
src/main/groovy/io/kamax/mxisd/config/StorageConfig.java
Normal file
51
src/main/groovy/io/kamax/mxisd/config/StorageConfig.java
Normal file
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import io.kamax.mxisd.exception.ConfigurationException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("storage")
|
||||
public class StorageConfig {
|
||||
|
||||
private String backend;
|
||||
|
||||
public String getBackend() {
|
||||
return backend;
|
||||
}
|
||||
|
||||
public void setBackend(String backend) {
|
||||
this.backend = backend;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void postConstruct() {
|
||||
if (StringUtils.isBlank(getBackend())) {
|
||||
throw new ConfigurationException("storage.backend");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
42
src/main/groovy/io/kamax/mxisd/config/ThymeleafConfig.java
Normal file
42
src/main/groovy/io/kamax/mxisd/config/ThymeleafConfig.java
Normal file
@@ -0,0 +1,42 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.thymeleaf.resourceresolver.FileResourceResolver;
|
||||
import org.thymeleaf.templateresolver.TemplateResolver;
|
||||
|
||||
@Configuration
|
||||
public class ThymeleafConfig {
|
||||
|
||||
@Bean
|
||||
public TemplateResolver getFileSystemResolver() {
|
||||
TemplateResolver resolver = new TemplateResolver();
|
||||
resolver.setPrefix("");
|
||||
resolver.setSuffix("");
|
||||
resolver.setCacheable(false);
|
||||
resolver.setOrder(1);
|
||||
resolver.setResourceResolver(new FileResourceResolver());
|
||||
return resolver;
|
||||
}
|
||||
|
||||
}
|
144
src/main/groovy/io/kamax/mxisd/config/ViewConfig.java
Normal file
144
src/main/groovy/io/kamax/mxisd/config/ViewConfig.java
Normal file
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("view")
|
||||
public class ViewConfig {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(ViewConfig.class);
|
||||
|
||||
public static class Session {
|
||||
|
||||
public static class Paths {
|
||||
|
||||
private String failure;
|
||||
private String success;
|
||||
|
||||
public String getFailure() {
|
||||
return failure;
|
||||
}
|
||||
|
||||
public void setFailure(String failure) {
|
||||
this.failure = failure;
|
||||
}
|
||||
|
||||
public String getSuccess() {
|
||||
return success;
|
||||
}
|
||||
|
||||
public void setSuccess(String success) {
|
||||
this.success = success;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Local {
|
||||
|
||||
private Paths onTokenSubmit = new Paths();
|
||||
|
||||
public Paths getOnTokenSubmit() {
|
||||
return onTokenSubmit;
|
||||
}
|
||||
|
||||
public void setOnTokenSubmit(Paths onTokenSubmit) {
|
||||
this.onTokenSubmit = onTokenSubmit;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Remote {
|
||||
|
||||
private Paths onRequest = new Paths();
|
||||
private Paths onCheck = new Paths();
|
||||
|
||||
public Paths getOnRequest() {
|
||||
return onRequest;
|
||||
}
|
||||
|
||||
public void setOnRequest(Paths onRequest) {
|
||||
this.onRequest = onRequest;
|
||||
}
|
||||
|
||||
public Paths getOnCheck() {
|
||||
return onCheck;
|
||||
}
|
||||
|
||||
public void setOnCheck(Paths onCheck) {
|
||||
this.onCheck = onCheck;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Local local = new Local();
|
||||
private Local localRemote = new Local();
|
||||
private Remote remote = new Remote();
|
||||
|
||||
public Local getLocal() {
|
||||
return local;
|
||||
}
|
||||
|
||||
public void setLocal(Local local) {
|
||||
this.local = local;
|
||||
}
|
||||
|
||||
public Local getLocalRemote() {
|
||||
return localRemote;
|
||||
}
|
||||
|
||||
public void setLocalRemote(Local localRemote) {
|
||||
this.localRemote = localRemote;
|
||||
}
|
||||
|
||||
public Remote getRemote() {
|
||||
return remote;
|
||||
}
|
||||
|
||||
public void setRemote(Remote remote) {
|
||||
this.remote = remote;
|
||||
}
|
||||
}
|
||||
|
||||
private Session session = new Session();
|
||||
|
||||
public Session getSession() {
|
||||
return session;
|
||||
}
|
||||
|
||||
public void setSession(Session session) {
|
||||
this.session = session;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- View config ---");
|
||||
log.info("Session: {}", new Gson().toJson(session));
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.ldap;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap.attribute")
|
||||
public class LdapAttributeConfig {
|
||||
|
||||
private LdapAttributeUidConfig uid;
|
||||
private String name;
|
||||
|
||||
public LdapAttributeUidConfig getUid() {
|
||||
return uid;
|
||||
}
|
||||
|
||||
public void setUid(LdapAttributeUidConfig uid) {
|
||||
this.uid = uid;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.ldap;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap.attribute.uid")
|
||||
public class LdapAttributeUidConfig {
|
||||
|
||||
private String type;
|
||||
private String value;
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getValue() {
|
||||
return value;
|
||||
}
|
||||
|
||||
public void setValue(String value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.ldap;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap.auth")
|
||||
public class LdapAuthConfig {
|
||||
|
||||
private String filter;
|
||||
|
||||
public String getFilter() {
|
||||
return filter;
|
||||
}
|
||||
|
||||
public void setFilter(String filter) {
|
||||
this.filter = filter;
|
||||
}
|
||||
|
||||
}
|
129
src/main/groovy/io/kamax/mxisd/config/ldap/LdapConfig.groovy
Normal file
129
src/main/groovy/io/kamax/mxisd/config/ldap/LdapConfig.groovy
Normal file
@@ -0,0 +1,129 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.ldap
|
||||
|
||||
import groovy.json.JsonOutput
|
||||
import io.kamax.mxisd.backend.ldap.LdapThreePidProvider
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties
|
||||
import org.springframework.context.annotation.Configuration
|
||||
|
||||
import javax.annotation.PostConstruct
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap")
|
||||
class LdapConfig {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(LdapConfig.class)
|
||||
|
||||
private boolean enabled
|
||||
|
||||
@Autowired
|
||||
private LdapConnectionConfig conn
|
||||
private LdapAttributeConfig attribute
|
||||
private LdapAuthConfig auth
|
||||
private LdapIdentityConfig identity
|
||||
|
||||
boolean isEnabled() {
|
||||
return enabled
|
||||
}
|
||||
|
||||
void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled
|
||||
}
|
||||
|
||||
LdapConnectionConfig getConn() {
|
||||
return conn
|
||||
}
|
||||
|
||||
void setConn(LdapConnectionConfig conn) {
|
||||
this.conn = conn
|
||||
}
|
||||
|
||||
LdapAttributeConfig getAttribute() {
|
||||
return attribute
|
||||
}
|
||||
|
||||
void setAttribute(LdapAttributeConfig attribute) {
|
||||
this.attribute = attribute
|
||||
}
|
||||
|
||||
LdapAuthConfig getAuth() {
|
||||
return auth
|
||||
}
|
||||
|
||||
void setAuth(LdapAuthConfig auth) {
|
||||
this.auth = auth
|
||||
}
|
||||
|
||||
LdapIdentityConfig getIdentity() {
|
||||
return identity
|
||||
}
|
||||
|
||||
void setIdentity(LdapIdentityConfig identity) {
|
||||
this.identity = identity
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
void afterPropertiesSet() {
|
||||
log.info("--- LDAP Config ---")
|
||||
log.info("Enabled: {}", isEnabled())
|
||||
|
||||
if (!isEnabled()) {
|
||||
return
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(conn.getHost())) {
|
||||
throw new IllegalStateException("LDAP Host must be configured!")
|
||||
}
|
||||
|
||||
if (1 > conn.getPort() || 65535 < conn.getPort()) {
|
||||
throw new IllegalStateException("LDAP port is not valid")
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(attribute.getUid().getType())) {
|
||||
throw new IllegalStateException("Attribute UID Type cannot be empty")
|
||||
}
|
||||
|
||||
|
||||
if (StringUtils.isBlank(attribute.getUid().getValue())) {
|
||||
throw new IllegalStateException("Attribute UID value cannot be empty")
|
||||
}
|
||||
|
||||
String uidType = attribute.getUid().getType();
|
||||
if (!StringUtils.equals(LdapThreePidProvider.UID, uidType) && !StringUtils.equals(LdapThreePidProvider.MATRIX_ID, uidType)) {
|
||||
throw new IllegalArgumentException("Unsupported LDAP UID type: " + uidType)
|
||||
}
|
||||
|
||||
log.info("Host: {}", conn.getHost())
|
||||
log.info("Port: {}", conn.getPort())
|
||||
log.info("Bind DN: {}", conn.getBindDn())
|
||||
log.info("Base DN: {}", conn.getBaseDn())
|
||||
|
||||
log.info("Attribute: {}", JsonOutput.toJson(attribute))
|
||||
log.info("Auth: {}", JsonOutput.toJson(auth))
|
||||
log.info("Identity: {}", JsonOutput.toJson(identity))
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.ldap;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap.connection")
|
||||
public class LdapConnectionConfig {
|
||||
|
||||
private boolean tls;
|
||||
private String host;
|
||||
private int port;
|
||||
private String bindDn;
|
||||
private String bindPassword;
|
||||
private String baseDn;
|
||||
|
||||
public boolean isTls() {
|
||||
return tls;
|
||||
}
|
||||
|
||||
public void setTls(boolean tls) {
|
||||
this.tls = tls;
|
||||
}
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void setHost(String host) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public String getBindDn() {
|
||||
return bindDn;
|
||||
}
|
||||
|
||||
public void setBindDn(String bindDn) {
|
||||
this.bindDn = bindDn;
|
||||
}
|
||||
|
||||
public String getBindPassword() {
|
||||
return bindPassword;
|
||||
}
|
||||
|
||||
public void setBindPassword(String bindPassword) {
|
||||
this.bindPassword = bindPassword;
|
||||
}
|
||||
|
||||
public String getBaseDn() {
|
||||
return baseDn;
|
||||
}
|
||||
|
||||
public void setBaseDn(String baseDn) {
|
||||
this.baseDn = baseDn;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.ldap;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "ldap.identity")
|
||||
public class LdapIdentityConfig {
|
||||
|
||||
private Map<String, String> medium = new HashMap<>();
|
||||
|
||||
public Map<String, String> getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public Optional<String> getQuery(String key) {
|
||||
return Optional.ofNullable(medium.get(key));
|
||||
}
|
||||
|
||||
public void setMedium(Map<String, String> medium) {
|
||||
this.medium = medium;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,149 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.rest;
|
||||
|
||||
import io.kamax.mxisd.exception.ConfigurationException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import java.net.MalformedURLException;
|
||||
import java.net.URL;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("rest")
|
||||
public class RestBackendConfig {
|
||||
|
||||
public static class IdentityEndpoints {
|
||||
|
||||
private String single;
|
||||
private String bulk;
|
||||
|
||||
public String getSingle() {
|
||||
return single;
|
||||
}
|
||||
|
||||
public void setSingle(String single) {
|
||||
this.single = single;
|
||||
}
|
||||
|
||||
public String getBulk() {
|
||||
return bulk;
|
||||
}
|
||||
|
||||
public void setBulk(String bulk) {
|
||||
this.bulk = bulk;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class Endpoints {
|
||||
|
||||
private IdentityEndpoints identity = new IdentityEndpoints();
|
||||
private String auth;
|
||||
|
||||
public IdentityEndpoints getIdentity() {
|
||||
return identity;
|
||||
}
|
||||
|
||||
public void setIdentity(IdentityEndpoints identity) {
|
||||
this.identity = identity;
|
||||
}
|
||||
|
||||
public String getAuth() {
|
||||
return auth;
|
||||
}
|
||||
|
||||
public void setAuth(String auth) {
|
||||
this.auth = auth;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(RestBackendConfig.class);
|
||||
|
||||
private boolean enabled;
|
||||
private String host;
|
||||
private Endpoints endpoints = new Endpoints();
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void setHost(String host) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public Endpoints getEndpoints() {
|
||||
return endpoints;
|
||||
}
|
||||
|
||||
public void setEndpoints(Endpoints endpoints) {
|
||||
this.endpoints = endpoints;
|
||||
}
|
||||
|
||||
private String buildEndpointUrl(String endpoint) {
|
||||
if (StringUtils.startsWith(endpoint, "/")) {
|
||||
if (StringUtils.isBlank(getHost())) {
|
||||
throw new ConfigurationException("rest.host");
|
||||
}
|
||||
|
||||
try {
|
||||
new URL(getHost());
|
||||
} catch (MalformedURLException e) {
|
||||
throw new ConfigurationException("rest.host", e.getMessage());
|
||||
}
|
||||
|
||||
return getHost() + endpoint;
|
||||
} else {
|
||||
return endpoint;
|
||||
}
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- REST backend config ---");
|
||||
log.info("Enabled: {}", isEnabled());
|
||||
|
||||
if (isEnabled()) {
|
||||
endpoints.setAuth(buildEndpointUrl(endpoints.getAuth()));
|
||||
endpoints.identity.setSingle(buildEndpointUrl(endpoints.identity.getSingle()));
|
||||
endpoints.identity.setBulk(buildEndpointUrl(endpoints.identity.getBulk()));
|
||||
|
||||
log.info("Host: {}", getHost());
|
||||
log.info("Auth endpoint: {}", endpoints.getAuth());
|
||||
log.info("Identity Single endpoint: {}", endpoints.identity.getSingle());
|
||||
log.info("Identity Bulk endpoint: {}", endpoints.identity.getBulk());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,21 @@
|
||||
package io.kamax.mxisd.config.sql;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
// Unused
|
||||
@Configuration
|
||||
@ConfigurationProperties("sql.auth")
|
||||
public class SqlProviderAuthConfig {
|
||||
|
||||
private boolean enabled;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.sql;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("sql")
|
||||
public class SqlProviderConfig {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(SqlProviderConfig.class);
|
||||
|
||||
private boolean enabled;
|
||||
private String type;
|
||||
private String connection;
|
||||
private SqlProviderAuthConfig auth;
|
||||
private SqlProviderIdentityConfig identity;
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getConnection() {
|
||||
return connection;
|
||||
}
|
||||
|
||||
public void setConnection(String connection) {
|
||||
this.connection = connection;
|
||||
}
|
||||
|
||||
public SqlProviderAuthConfig getAuth() {
|
||||
return auth;
|
||||
}
|
||||
|
||||
public void setAuth(SqlProviderAuthConfig auth) {
|
||||
this.auth = auth;
|
||||
}
|
||||
|
||||
public SqlProviderIdentityConfig getIdentity() {
|
||||
return identity;
|
||||
}
|
||||
|
||||
public void setIdentity(SqlProviderIdentityConfig identity) {
|
||||
this.identity = identity;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void postConstruct() {
|
||||
log.info("--- SQL Provider config ---");
|
||||
log.info("Enabled: {}", isEnabled());
|
||||
if (isEnabled()) {
|
||||
log.info("Type: {}", getType());
|
||||
log.info("Connection: {}", getConnection());
|
||||
log.info("Auth enabled: {}", getAuth().isEnabled());
|
||||
log.info("Identy type: {}", getIdentity().getType());
|
||||
log.info("Identity medium queries: {}", new Gson().toJson(getIdentity().getMedium()));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.sql;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("sql.identity")
|
||||
public class SqlProviderIdentityConfig {
|
||||
|
||||
private String type;
|
||||
private String query;
|
||||
private Map<String, String> medium = new HashMap<>();
|
||||
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
public String getQuery() {
|
||||
return query;
|
||||
}
|
||||
|
||||
public void setQuery(String query) {
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
public Map<String, String> getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public void setMedium(Map<String, String> medium) {
|
||||
this.medium = medium;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,93 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.threepid.connector;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "threepid.medium.email.connectors.smtp")
|
||||
public class EmailSmtpConfig {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(EmailSmtpConfig.class);
|
||||
|
||||
private String host;
|
||||
private int port;
|
||||
private int tls;
|
||||
private String login;
|
||||
private String password;
|
||||
|
||||
public String getHost() {
|
||||
return host;
|
||||
}
|
||||
|
||||
public void setHost(String host) {
|
||||
this.host = host;
|
||||
}
|
||||
|
||||
public int getPort() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public void setPort(int port) {
|
||||
this.port = port;
|
||||
}
|
||||
|
||||
public int getTls() {
|
||||
return tls;
|
||||
}
|
||||
|
||||
public void setTls(int tls) {
|
||||
this.tls = tls;
|
||||
}
|
||||
|
||||
public String getLogin() {
|
||||
return login;
|
||||
}
|
||||
|
||||
public void setLogin(String login) {
|
||||
this.login = login;
|
||||
}
|
||||
|
||||
public String getPassword() {
|
||||
return password;
|
||||
}
|
||||
|
||||
public void setPassword(String password) {
|
||||
this.password = password;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- E-mail SMTP Connector config ---");
|
||||
log.info("Host: {}", getHost());
|
||||
log.info("Port: {}", getPort());
|
||||
log.info("TLS Mode: {}", getTls());
|
||||
log.info("Login: {}", getLogin());
|
||||
log.info("Has password: {}", StringUtils.isNotBlank(getPassword()));
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.threepid.medium;
|
||||
|
||||
import io.kamax.mxisd.config.MatrixConfig;
|
||||
import io.kamax.mxisd.exception.ConfigurationException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.commons.lang.WordUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("threepid.medium.email")
|
||||
public class EmailConfig {
|
||||
|
||||
public static class Identity {
|
||||
private String from;
|
||||
private String name;
|
||||
|
||||
public String getFrom() {
|
||||
return from;
|
||||
}
|
||||
|
||||
public void setFrom(String from) {
|
||||
this.from = from;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String generator;
|
||||
private String connector;
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(EmailConfig.class);
|
||||
|
||||
private MatrixConfig mxCfg;
|
||||
private Identity identity = new Identity();
|
||||
|
||||
@Autowired
|
||||
public EmailConfig(MatrixConfig mxCfg) {
|
||||
this.mxCfg = mxCfg;
|
||||
}
|
||||
|
||||
public Identity getIdentity() {
|
||||
return identity;
|
||||
}
|
||||
|
||||
public String getGenerator() {
|
||||
return generator;
|
||||
}
|
||||
|
||||
public void setGenerator(String generator) {
|
||||
this.generator = generator;
|
||||
}
|
||||
|
||||
public String getConnector() {
|
||||
return connector;
|
||||
}
|
||||
|
||||
public void setConnector(String connector) {
|
||||
this.connector = connector;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- E-mail config ---");
|
||||
|
||||
if (StringUtils.isBlank(getGenerator())) {
|
||||
throw new ConfigurationException("generator");
|
||||
}
|
||||
|
||||
if (StringUtils.isBlank(getConnector())) {
|
||||
throw new ConfigurationException("connector");
|
||||
}
|
||||
|
||||
log.info("From: {}", identity.getFrom());
|
||||
|
||||
if (StringUtils.isBlank(identity.getName())) {
|
||||
identity.setName(WordUtils.capitalize(mxCfg.getDomain()) + " Identity Server");
|
||||
}
|
||||
log.info("Name: {}", identity.getName());
|
||||
log.info("Generator: {}", getGenerator());
|
||||
log.info("Connector: {}", getConnector());
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.config.threepid.medium;
|
||||
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
|
||||
@Configuration
|
||||
@ConfigurationProperties("threepid.medium.email.generators.template")
|
||||
public class EmailTemplateConfig {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(EmailTemplateConfig.class);
|
||||
private static final String classpathPrefix = "classpath:";
|
||||
|
||||
private static String getName(String path) {
|
||||
if (StringUtils.startsWith(path, classpathPrefix)) {
|
||||
return "Built-in (" + path.substring(classpathPrefix.length()) + ")";
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
public static class Session {
|
||||
|
||||
public static class SessionValidation {
|
||||
|
||||
private String local;
|
||||
private String remote;
|
||||
|
||||
public String getLocal() {
|
||||
return local;
|
||||
}
|
||||
|
||||
public void setLocal(String local) {
|
||||
this.local = local;
|
||||
}
|
||||
|
||||
public String getRemote() {
|
||||
return remote;
|
||||
}
|
||||
|
||||
public void setRemote(String remote) {
|
||||
this.remote = remote;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private SessionValidation validation;
|
||||
|
||||
public SessionValidation getValidation() {
|
||||
return validation;
|
||||
}
|
||||
|
||||
public void setValidation(SessionValidation validation) {
|
||||
this.validation = validation;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private String invite;
|
||||
private Session session = new Session();
|
||||
|
||||
public String getInvite() {
|
||||
return invite;
|
||||
}
|
||||
|
||||
public void setInvite(String invite) {
|
||||
this.invite = invite;
|
||||
}
|
||||
|
||||
public Session getSession() {
|
||||
return session;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void build() {
|
||||
log.info("--- E-mail Generator templates config ---");
|
||||
log.info("Invite: {}", getName(getInvite()));
|
||||
log.info("Session validation:");
|
||||
log.info("\tLocal: {}", getName(getSession().getValidation().getLocal()));
|
||||
log.info("\tRemote: {}", getName(getSession().getValidation().getRemote()));
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonElement;
|
||||
import com.google.gson.JsonObject;
|
||||
import com.google.gson.JsonParser;
|
||||
import io.kamax.mxisd.auth.AuthManager;
|
||||
import io.kamax.mxisd.auth.UserAuthResult;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMethod;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
public class AuthController {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(AuthController.class);
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
@Autowired
|
||||
private AuthManager mgr;
|
||||
|
||||
@RequestMapping(value = "/_matrix-internal/identity/v1/check_credentials", method = RequestMethod.POST)
|
||||
public String checkCredentials(HttpServletRequest req) {
|
||||
try {
|
||||
JsonElement el = new JsonParser().parse(IOUtils.toString(req.getInputStream(), StandardCharsets.UTF_8));
|
||||
if (!el.isJsonObject() || !el.getAsJsonObject().has("user")) {
|
||||
throw new IllegalArgumentException("Missing user key");
|
||||
}
|
||||
|
||||
JsonObject authData = el.getAsJsonObject().get("user").getAsJsonObject();
|
||||
if (!authData.has("id") || !authData.has("password")) {
|
||||
throw new IllegalArgumentException("Missing id or password keys");
|
||||
}
|
||||
|
||||
String id = authData.get("id").getAsString();
|
||||
log.info("Requested to check credentials for {}", id);
|
||||
String password = authData.get("password").getAsString();
|
||||
|
||||
UserAuthResult result = mgr.authenticate(id, password);
|
||||
|
||||
JsonObject authObj = new JsonObject();
|
||||
authObj.addProperty("success", result.isSuccess());
|
||||
if (result.isSuccess()) {
|
||||
authObj.addProperty("mxid", result.getMxid());
|
||||
authObj.addProperty("display_name", result.getDisplayName());
|
||||
}
|
||||
JsonObject obj = new JsonObject();
|
||||
|
||||
obj.add("authentication", authObj);
|
||||
return gson.toJson(obj);
|
||||
} catch (IOException e) {
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import io.kamax.mxisd.exception.BadRequestException;
|
||||
import io.kamax.mxisd.exception.InternalServerError;
|
||||
import io.kamax.mxisd.exception.MappingAlreadyExistsException;
|
||||
import io.kamax.mxisd.exception.MatrixException;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.MissingServletRequestParameterException;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.time.Instant;
|
||||
|
||||
@ControllerAdvice
|
||||
@ResponseBody
|
||||
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
public class DefaultExceptionHandler {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(DefaultExceptionHandler.class);
|
||||
|
||||
private static Gson gson = new Gson();
|
||||
|
||||
static String handle(String erroCode, String error) {
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("errcode", erroCode);
|
||||
obj.addProperty("error", error);
|
||||
return gson.toJson(obj);
|
||||
}
|
||||
|
||||
@ExceptionHandler(InternalServerError.class)
|
||||
public String handle(InternalServerError e, HttpServletResponse response) {
|
||||
if (StringUtils.isNotBlank(e.getInternalReason())) {
|
||||
log.error("Reference #{} - {}", e.getReference(), e.getInternalReason());
|
||||
} else {
|
||||
log.error("Reference #{}", e);
|
||||
}
|
||||
|
||||
return handleGeneric(e, response);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MatrixException.class)
|
||||
public String handleGeneric(MatrixException e, HttpServletResponse response) {
|
||||
response.setStatus(e.getStatus());
|
||||
return handle(e.getErrorCode(), e.getError());
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler(MissingServletRequestParameterException.class)
|
||||
public String handle(MissingServletRequestParameterException e) {
|
||||
return handle("M_INVALID_BODY", e.getMessage());
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler(MappingAlreadyExistsException.class)
|
||||
public String handle(MappingAlreadyExistsException e) {
|
||||
return handle("M_ALREADY_EXISTS", e.getMessage());
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
@ExceptionHandler(BadRequestException.class)
|
||||
public String handle(BadRequestException e) {
|
||||
return handle("M_BAD_REQUEST", e.getMessage());
|
||||
}
|
||||
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
public String handle(HttpServletRequest req, RuntimeException e) {
|
||||
log.error("Unknown error when handling {}", req.getRequestURL(), e);
|
||||
return handle(
|
||||
"M_UNKNOWN",
|
||||
StringUtils.defaultIfBlank(
|
||||
e.getMessage(),
|
||||
"An internal server error occured. If this error persists, please contact support with reference #" +
|
||||
Instant.now().toEpochMilli()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1;
|
||||
|
||||
public class IdentityAPIv1 {
|
||||
|
||||
public static final String BASE = "/_matrix/identity/api/v1";
|
||||
|
||||
}
|
@@ -20,10 +20,22 @@
|
||||
|
||||
package io.kamax.mxisd.controller.v1
|
||||
|
||||
import io.kamax.mxisd.exception.NotImplementedException
|
||||
import com.google.gson.Gson
|
||||
import io.kamax.matrix.MatrixID
|
||||
import io.kamax.mxisd.config.ServerConfig
|
||||
import io.kamax.mxisd.controller.v1.io.ThreePidInviteReplyIO
|
||||
import io.kamax.mxisd.invitation.IThreePidInvite
|
||||
import io.kamax.mxisd.invitation.IThreePidInviteReply
|
||||
import io.kamax.mxisd.invitation.InvitationManager
|
||||
import io.kamax.mxisd.invitation.ThreePidInvite
|
||||
import io.kamax.mxisd.key.KeyManager
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.web.bind.annotation.CrossOrigin
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RequestParam
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
@@ -31,15 +43,38 @@ import javax.servlet.http.HttpServletRequest
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.POST
|
||||
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping(path = IdentityAPIv1.BASE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
class InvitationController {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(InvitationController.class)
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/store-invite", method = POST)
|
||||
String store(HttpServletRequest request) {
|
||||
log.error("{} was requested but not implemented", request.getRequestURL())
|
||||
@Autowired
|
||||
private InvitationManager mgr
|
||||
|
||||
throw new NotImplementedException()
|
||||
@Autowired
|
||||
private KeyManager keyMgr
|
||||
|
||||
@Autowired
|
||||
private ServerConfig srvCfg
|
||||
|
||||
private Gson gson = new Gson()
|
||||
|
||||
@RequestMapping(value = "/store-invite", method = POST)
|
||||
String store(
|
||||
HttpServletRequest request,
|
||||
@RequestParam String sender,
|
||||
@RequestParam String medium,
|
||||
@RequestParam String address,
|
||||
@RequestParam("room_id") String roomId) {
|
||||
Map<String, String> parameters = new HashMap<>()
|
||||
for (String key : request.getParameterMap().keySet()) {
|
||||
parameters.put(key, request.getParameter(key));
|
||||
}
|
||||
IThreePidInvite invite = new ThreePidInvite(new MatrixID(sender), medium, address, roomId, parameters)
|
||||
IThreePidInviteReply reply = mgr.storeInvite(invite)
|
||||
|
||||
return gson.toJson(new ThreePidInviteReplyIO(reply, keyMgr.getPublicKeyBase64(keyMgr.getCurrentIndex()), srvCfg.getPublicUrl()))
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -20,22 +20,25 @@
|
||||
|
||||
package io.kamax.mxisd.controller.v1
|
||||
|
||||
import com.google.gson.Gson
|
||||
import groovy.json.JsonOutput
|
||||
import io.kamax.mxisd.controller.v1.io.KeyValidityJson
|
||||
import io.kamax.mxisd.exception.BadRequestException
|
||||
import io.kamax.mxisd.exception.NotImplementedException
|
||||
import io.kamax.mxisd.key.KeyManager
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.web.bind.annotation.PathVariable
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.web.bind.annotation.*
|
||||
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.GET
|
||||
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping(path = IdentityAPIv1.BASE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
class KeyController {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(KeyController.class)
|
||||
@@ -43,29 +46,36 @@ class KeyController {
|
||||
@Autowired
|
||||
private KeyManager keyMgr
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/pubkey/{keyType}:{keyId}", method = GET)
|
||||
private Gson gson = new Gson();
|
||||
private String validKey = gson.toJson(new KeyValidityJson(true));
|
||||
private String invalidKey = gson.toJson(new KeyValidityJson(false));
|
||||
|
||||
@RequestMapping(value = "/pubkey/{keyType}:{keyId}", method = GET)
|
||||
String getKey(@PathVariable String keyType, @PathVariable int keyId) {
|
||||
if (!"ed25519".contentEquals(keyType)) {
|
||||
throw new BadRequestException("Invalid algorithm: " + keyType)
|
||||
}
|
||||
|
||||
log.info("Key {}:{} was requested", keyType, keyId)
|
||||
return JsonOutput.toJson([
|
||||
public_key: keyMgr.getPublicKeyBase64(keyId)
|
||||
])
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/pubkey/ephemeral/isvalid", method = GET)
|
||||
@RequestMapping(value = "/pubkey/ephemeral/isvalid", method = GET)
|
||||
String checkEphemeralKeyValidity(HttpServletRequest request) {
|
||||
log.error("{} was requested but not implemented", request.getRequestURL())
|
||||
log.warn("Ephemeral key was request but no ephemeral key are generated, replying not valid")
|
||||
|
||||
throw new NotImplementedException()
|
||||
return invalidKey
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/pubkey/isvalid", method = GET)
|
||||
String checkKeyValidity(HttpServletRequest request) {
|
||||
log.error("{} was requested but not implemented", request.getRequestURL())
|
||||
@RequestMapping(value = "/pubkey/isvalid", method = GET)
|
||||
String checkKeyValidity(HttpServletRequest request, @RequestParam("public_key") String pubKey) {
|
||||
log.info("Validating public key {}", pubKey)
|
||||
|
||||
throw new NotImplementedException()
|
||||
// TODO do in manager
|
||||
boolean valid = StringUtils.equals(pubKey, keyMgr.getPublicKeyBase64(keyMgr.getCurrentIndex()))
|
||||
return valid ? validKey : invalidKey
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -20,17 +20,20 @@
|
||||
|
||||
package io.kamax.mxisd.controller.v1
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import groovy.json.JsonOutput
|
||||
import groovy.json.JsonSlurper
|
||||
import io.kamax.mxisd.lookup.BulkLookupRequest
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping
|
||||
import io.kamax.mxisd.controller.v1.io.SingeLookupReplyJson
|
||||
import io.kamax.mxisd.lookup.*
|
||||
import io.kamax.mxisd.lookup.strategy.LookupStrategy
|
||||
import io.kamax.mxisd.signature.SignatureManager
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.http.MediaType
|
||||
import org.springframework.web.bind.annotation.CrossOrigin
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RequestParam
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
@@ -41,10 +44,13 @@ import static org.springframework.web.bind.annotation.RequestMethod.GET
|
||||
import static org.springframework.web.bind.annotation.RequestMethod.POST
|
||||
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping(path = IdentityAPIv1.BASE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
class MappingController {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(MappingController.class)
|
||||
private JsonSlurper json = new JsonSlurper()
|
||||
private Gson gson = new Gson()
|
||||
|
||||
@Autowired
|
||||
private LookupStrategy strategy
|
||||
@@ -52,38 +58,50 @@ class MappingController {
|
||||
@Autowired
|
||||
private SignatureManager signMgr
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/lookup", method = GET)
|
||||
String lookup(HttpServletRequest request, @RequestParam String medium, @RequestParam String address) {
|
||||
String remote = StringUtils.defaultIfBlank(request.getHeader("X-FORWARDED-FOR"), request.getRemoteAddr())
|
||||
log.info("Got request from {}", remote)
|
||||
private void setRequesterInfo(ALookupRequest lookupReq, HttpServletRequest req) {
|
||||
lookupReq.setRequester(req.getRemoteAddr())
|
||||
String xff = req.getHeader("X-FORWARDED-FOR")
|
||||
lookupReq.setRecursive(StringUtils.isNotBlank(xff))
|
||||
if (lookupReq.isRecursive()) {
|
||||
lookupReq.setRecurseHosts(Arrays.asList(xff.split(",")))
|
||||
}
|
||||
|
||||
lookupReq.setUserAgent(req.getHeader("USER-AGENT"))
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/lookup", method = GET)
|
||||
String lookup(HttpServletRequest request, @RequestParam String medium, @RequestParam String address) {
|
||||
SingleLookupRequest lookupRequest = new SingleLookupRequest()
|
||||
lookupRequest.setRequester(remote)
|
||||
setRequesterInfo(lookupRequest, request)
|
||||
lookupRequest.setType(medium)
|
||||
lookupRequest.setThreePid(address)
|
||||
|
||||
Optional<?> lookupOpt = strategy.find(lookupRequest)
|
||||
log.info("Got single lookup request from {} with client {} - Is recursive? {}", lookupRequest.getRequester(), lookupRequest.getUserAgent(), lookupRequest.isRecursive())
|
||||
|
||||
Optional<SingleLookupReply> lookupOpt = strategy.find(lookupRequest)
|
||||
if (!lookupOpt.isPresent()) {
|
||||
log.info("No mapping was found, return empty JSON object")
|
||||
return JsonOutput.toJson([])
|
||||
}
|
||||
|
||||
def lookup = lookupOpt.get()
|
||||
if (lookup['signatures'] == null) {
|
||||
log.info("lookup is not signed yet, we sign it")
|
||||
lookup['signatures'] = signMgr.signMessage(JsonOutput.toJson(lookup))
|
||||
SingleLookupReply lookup = lookupOpt.get()
|
||||
if (lookup.isSigned()) {
|
||||
log.info("Lookup is already signed, sending as-is")
|
||||
return lookup.getBody();
|
||||
} else {
|
||||
log.info("Lookup is not signed, signing")
|
||||
JsonObject obj = new Gson().toJsonTree(new SingeLookupReplyJson(lookup)).getAsJsonObject()
|
||||
obj.add("signatures", signMgr.signMessageGson(gson.toJson(obj)))
|
||||
|
||||
return gson.toJson(obj)
|
||||
}
|
||||
}
|
||||
|
||||
return JsonOutput.toJson(lookup)
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/bulk_lookup", method = POST)
|
||||
@RequestMapping(value = "/bulk_lookup", method = POST)
|
||||
String bulkLookup(HttpServletRequest request) {
|
||||
String remote = StringUtils.defaultIfBlank(request.getHeader("X-FORWARDED-FOR"), request.getRemoteAddr())
|
||||
log.info("Got request from {}", remote)
|
||||
|
||||
BulkLookupRequest lookupRequest = new BulkLookupRequest()
|
||||
lookupRequest.setRequester(remote)
|
||||
setRequesterInfo(lookupRequest, request)
|
||||
log.info("Got single lookup request from {} with client {} - Is recursive? {}", lookupRequest.getRequester(), lookupRequest.getUserAgent(), lookupRequest.isRecursive())
|
||||
|
||||
ClientBulkLookupRequest input = (ClientBulkLookupRequest) json.parseText(request.getInputStream().getText())
|
||||
List<ThreePidMapping> mappings = new ArrayList<>()
|
||||
|
@@ -20,135 +20,63 @@
|
||||
|
||||
package io.kamax.mxisd.controller.v1
|
||||
|
||||
import com.google.gson.Gson
|
||||
import com.google.gson.JsonObject
|
||||
import io.kamax.mxisd.controller.v1.io.SessionEmailTokenRequestJson
|
||||
import io.kamax.mxisd.controller.v1.io.SessionPhoneTokenRequestJson
|
||||
import io.kamax.mxisd.exception.BadRequestException
|
||||
import io.kamax.mxisd.lookup.ThreePid
|
||||
import io.kamax.mxisd.mapping.MappingManager
|
||||
import org.apache.commons.io.IOUtils
|
||||
import org.apache.commons.lang.StringUtils
|
||||
import org.apache.http.HttpStatus
|
||||
import io.kamax.mxisd.config.ServerConfig
|
||||
import io.kamax.mxisd.config.ViewConfig
|
||||
import io.kamax.mxisd.controller.v1.remote.RemoteIdentityAPIv1
|
||||
import io.kamax.mxisd.session.SessionMananger
|
||||
import io.kamax.mxisd.session.ValidationResult
|
||||
import org.slf4j.Logger
|
||||
import org.slf4j.LoggerFactory
|
||||
import org.springframework.beans.factory.annotation.Autowired
|
||||
import org.springframework.web.bind.annotation.PathVariable
|
||||
import org.springframework.stereotype.Controller
|
||||
import org.springframework.ui.Model
|
||||
import org.springframework.web.bind.annotation.RequestMapping
|
||||
import org.springframework.web.bind.annotation.RequestParam
|
||||
import org.springframework.web.bind.annotation.RestController
|
||||
|
||||
import javax.servlet.http.HttpServletRequest
|
||||
import javax.servlet.http.HttpServletResponse
|
||||
import java.nio.charset.StandardCharsets
|
||||
|
||||
@RestController
|
||||
@Controller
|
||||
@RequestMapping(path = IdentityAPIv1.BASE)
|
||||
class SessionController {
|
||||
|
||||
@Autowired
|
||||
private MappingManager mgr
|
||||
|
||||
private Gson gson = new Gson()
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(SessionController.class)
|
||||
|
||||
private <T> T fromJson(HttpServletRequest req, Class<T> obj) {
|
||||
gson.fromJson(new InputStreamReader(req.getInputStream(), StandardCharsets.UTF_8), obj)
|
||||
}
|
||||
@Autowired
|
||||
private ServerConfig srvCfg;
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/validate/{medium}/requestToken")
|
||||
String init(HttpServletRequest request, HttpServletResponse response, @PathVariable String medium) {
|
||||
log.info("Requested: {}", request.getRequestURL(), request.getQueryString())
|
||||
@Autowired
|
||||
private SessionMananger mgr
|
||||
|
||||
if (StringUtils.equals("email", medium)) {
|
||||
SessionEmailTokenRequestJson req = fromJson(request, SessionEmailTokenRequestJson.class)
|
||||
return gson.toJson(new Sid(mgr.create(req)))
|
||||
}
|
||||
@Autowired
|
||||
private ViewConfig viewCfg;
|
||||
|
||||
if (StringUtils.equals("msisdn", medium)) {
|
||||
SessionPhoneTokenRequestJson req = fromJson(request, SessionPhoneTokenRequestJson.class)
|
||||
return gson.toJson(new Sid(mgr.create(req)))
|
||||
}
|
||||
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("errcode", "M_INVALID_3PID_TYPE")
|
||||
obj.addProperty("error", medium + " is not supported as a 3PID type")
|
||||
response.setStatus(HttpStatus.SC_BAD_REQUEST)
|
||||
return gson.toJson(obj)
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/validate/{medium}/submitToken")
|
||||
String validate(HttpServletRequest request,
|
||||
@RequestMapping(value = "/validate/{medium}/submitToken")
|
||||
String validate(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
@RequestParam String sid,
|
||||
@RequestParam("client_secret") String secret, @RequestParam String token) {
|
||||
@RequestParam("client_secret") String secret,
|
||||
@RequestParam String token,
|
||||
Model model
|
||||
) {
|
||||
log.info("Requested: {}?{}", request.getRequestURL(), request.getQueryString())
|
||||
|
||||
mgr.validate(sid, secret, token)
|
||||
|
||||
return "{}"
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/3pid/getValidated3pid")
|
||||
String check(HttpServletRequest request, HttpServletResponse response,
|
||||
@RequestParam String sid, @RequestParam("client_secret") String secret) {
|
||||
log.info("Requested: {}?{}", request.getRequestURL(), request.getQueryString())
|
||||
|
||||
Optional<ThreePid> result = mgr.getValidated(sid, secret)
|
||||
if (result.isPresent()) {
|
||||
log.info("requested session was validated")
|
||||
ThreePid pid = result.get()
|
||||
|
||||
JsonObject obj = new JsonObject()
|
||||
obj.addProperty("medium", pid.getMedium())
|
||||
obj.addProperty("address", pid.getAddress())
|
||||
obj.addProperty("validated_at", pid.getValidation().toEpochMilli())
|
||||
|
||||
return gson.toJson(obj);
|
||||
ValidationResult r = mgr.validate(sid, secret, token)
|
||||
log.info("Session {} was validated", sid)
|
||||
if (r.getNextUrl().isPresent()) {
|
||||
String url = srvCfg.getPublicUrl() + r.getNextUrl().get()
|
||||
log.info("Session {} validation: next URL is present, redirecting to {}", sid, url)
|
||||
response.sendRedirect(url)
|
||||
} else {
|
||||
log.info("requested session was not validated")
|
||||
|
||||
JsonObject obj = new JsonObject()
|
||||
obj.addProperty("errcode", "M_SESSION_NOT_VALIDATED")
|
||||
obj.addProperty("error", "sid, secret or session not valid")
|
||||
response.setStatus(HttpStatus.SC_BAD_REQUEST)
|
||||
return gson.toJson(obj)
|
||||
if (r.isCanRemote()) {
|
||||
String url = srvCfg.getPublicUrl() + RemoteIdentityAPIv1.getRequestToken(r.getSession().getId(), r.getSession().getSecret());
|
||||
model.addAttribute("remoteSessionLink", url)
|
||||
return viewCfg.getSession().getLocalRemote().getOnTokenSubmit().getSuccess()
|
||||
} else {
|
||||
return viewCfg.getSession().getLocal().getOnTokenSubmit().getSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/api/v1/3pid/bind")
|
||||
String bind(HttpServletRequest request, HttpServletResponse response,
|
||||
@RequestParam String sid, @RequestParam("client_secret") String secret, @RequestParam String mxid) {
|
||||
String data = IOUtils.toString(request.getReader())
|
||||
log.info("Requested: {}", request.getRequestURL(), request.getQueryString())
|
||||
try {
|
||||
mgr.bind(sid, secret, mxid)
|
||||
return "{}"
|
||||
} catch (BadRequestException e) {
|
||||
log.info("requested session was not validated")
|
||||
|
||||
JsonObject obj = new JsonObject()
|
||||
obj.addProperty("errcode", "M_SESSION_NOT_VALIDATED")
|
||||
obj.addProperty("error", e.getMessage())
|
||||
response.setStatus(HttpStatus.SC_BAD_REQUEST)
|
||||
return gson.toJson(obj)
|
||||
}
|
||||
}
|
||||
|
||||
private class Sid {
|
||||
|
||||
private String sid;
|
||||
|
||||
public Sid(String sid) {
|
||||
setSid(sid);
|
||||
}
|
||||
|
||||
String getSid() {
|
||||
return sid
|
||||
}
|
||||
|
||||
void setSid(String sid) {
|
||||
this.sid = sid
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,159 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import io.kamax.matrix.ThreePidMedium;
|
||||
import io.kamax.mxisd.ThreePid;
|
||||
import io.kamax.mxisd.config.ServerConfig;
|
||||
import io.kamax.mxisd.config.ViewConfig;
|
||||
import io.kamax.mxisd.controller.v1.io.SessionEmailTokenRequestJson;
|
||||
import io.kamax.mxisd.controller.v1.io.SessionPhoneTokenRequestJson;
|
||||
import io.kamax.mxisd.exception.BadRequestException;
|
||||
import io.kamax.mxisd.exception.SessionNotValidatedException;
|
||||
import io.kamax.mxisd.invitation.InvitationManager;
|
||||
import io.kamax.mxisd.lookup.ThreePidValidation;
|
||||
import io.kamax.mxisd.session.SessionMananger;
|
||||
import io.kamax.mxisd.util.GsonParser;
|
||||
import org.apache.http.HttpStatus;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.IOException;
|
||||
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping(path = IdentityAPIv1.BASE, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
public class SessionRestController {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(SessionRestController.class);
|
||||
|
||||
private class Sid { // FIXME replace with RequestTokenResponse
|
||||
|
||||
private String sid;
|
||||
|
||||
public Sid(String sid) {
|
||||
setSid(sid);
|
||||
}
|
||||
|
||||
String getSid() {
|
||||
return sid;
|
||||
}
|
||||
|
||||
void setSid(String sid) {
|
||||
this.sid = sid;
|
||||
}
|
||||
}
|
||||
|
||||
@Autowired
|
||||
private ServerConfig srvCfg;
|
||||
|
||||
@Autowired
|
||||
private SessionMananger mgr;
|
||||
|
||||
@Autowired
|
||||
private InvitationManager invMgr;
|
||||
|
||||
@Autowired
|
||||
private ViewConfig viewCfg;
|
||||
|
||||
private Gson gson = new Gson();
|
||||
private GsonParser parser = new GsonParser(gson);
|
||||
|
||||
@RequestMapping(value = "/validate/{medium}/requestToken")
|
||||
String init(HttpServletRequest request, HttpServletResponse response, @PathVariable String medium) throws IOException {
|
||||
log.info("Request {}: {}", request.getMethod(), request.getRequestURL(), request.getQueryString());
|
||||
if (ThreePidMedium.Email.is(medium)) {
|
||||
SessionEmailTokenRequestJson req = parser.parse(request, SessionEmailTokenRequestJson.class);
|
||||
return gson.toJson(new Sid(mgr.create(
|
||||
request.getRemoteHost(),
|
||||
new ThreePid(req.getMedium(), req.getValue()),
|
||||
req.getSecret(),
|
||||
req.getAttempt(),
|
||||
req.getNextLink())));
|
||||
}
|
||||
|
||||
if (ThreePidMedium.PhoneNumber.is(medium)) {
|
||||
SessionPhoneTokenRequestJson req = parser.parse(request, SessionPhoneTokenRequestJson.class);
|
||||
return gson.toJson(new Sid(mgr.create(
|
||||
request.getRemoteHost(),
|
||||
new ThreePid(req.getMedium(), req.getValue()),
|
||||
req.getSecret(),
|
||||
req.getAttempt(),
|
||||
req.getNextLink())));
|
||||
}
|
||||
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("errcode", "M_INVALID_3PID_TYPE");
|
||||
obj.addProperty("error", medium + " is not supported as a 3PID type");
|
||||
response.setStatus(HttpStatus.SC_BAD_REQUEST);
|
||||
return gson.toJson(obj);
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/3pid/getValidated3pid")
|
||||
String check(HttpServletRequest request, HttpServletResponse response,
|
||||
@RequestParam String sid, @RequestParam("client_secret") String secret) {
|
||||
log.info("Requested: {}", request.getRequestURL(), request.getQueryString());
|
||||
|
||||
try {
|
||||
ThreePidValidation pid = mgr.getValidated(sid, secret);
|
||||
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("medium", pid.getMedium());
|
||||
obj.addProperty("address", pid.getAddress());
|
||||
obj.addProperty("validated_at", pid.getValidation().toEpochMilli());
|
||||
|
||||
return gson.toJson(obj);
|
||||
} catch (SessionNotValidatedException e) {
|
||||
log.info("Session {} was requested but has not yet been validated", sid);
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
@RequestMapping(value = "/3pid/bind")
|
||||
String bind(HttpServletRequest request, HttpServletResponse response,
|
||||
@RequestParam String sid, @RequestParam("client_secret") String secret, @RequestParam String mxid) {
|
||||
log.info("Requested: {}", request.getRequestURL(), request.getQueryString());
|
||||
try {
|
||||
mgr.bind(sid, secret, mxid);
|
||||
return "{}";
|
||||
} catch (BadRequestException e) {
|
||||
log.info("requested session was not validated");
|
||||
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.addProperty("errcode", "M_SESSION_NOT_VALIDATED");
|
||||
obj.addProperty("error", e.getMessage());
|
||||
response.setStatus(HttpStatus.SC_BAD_REQUEST);
|
||||
return gson.toJson(obj);
|
||||
} finally {
|
||||
// If a user registers, there is no standard login event. Instead, this is the only way to trigger
|
||||
// resolution at an appropriate time. Meh at synapse/Riot!
|
||||
invMgr.lookupMappingsForInvites();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonObject;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.CrossOrigin;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@CrossOrigin
|
||||
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
|
||||
public class StatusController {
|
||||
|
||||
private Gson gson = new Gson();
|
||||
|
||||
@RequestMapping(value = "/_matrix/identity/status")
|
||||
public String getStatus() {
|
||||
// TODO link to backend
|
||||
JsonObject status = new JsonObject();
|
||||
status.addProperty("health", "OK");
|
||||
|
||||
JsonObject obj = new JsonObject();
|
||||
obj.add("status", status);
|
||||
|
||||
return gson.toJson(obj);
|
||||
}
|
||||
|
||||
}
|
@@ -1,12 +1,30 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
import io.kamax.mxisd.mapping.MappingSession;
|
||||
|
||||
public abstract class GenericTokenRequestJson implements MappingSession {
|
||||
public abstract class GenericTokenRequestJson {
|
||||
|
||||
private String client_secret;
|
||||
private int send_attempt;
|
||||
private String id_server;
|
||||
private String next_link;
|
||||
|
||||
public String getSecret() {
|
||||
return client_secret;
|
||||
@@ -16,8 +34,8 @@ public abstract class GenericTokenRequestJson implements MappingSession {
|
||||
return send_attempt;
|
||||
}
|
||||
|
||||
public String getServer() {
|
||||
return id_server;
|
||||
public String getNextLink() {
|
||||
return next_link;
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
public class KeyValidityJson {
|
||||
|
||||
private boolean valid;
|
||||
|
||||
public KeyValidityJson(boolean isValid) {
|
||||
this.valid = isValid;
|
||||
}
|
||||
|
||||
public boolean isValid() {
|
||||
return valid;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
public class RequestTokenResponse {
|
||||
|
||||
private String sid;
|
||||
|
||||
public String getSid() {
|
||||
return sid;
|
||||
}
|
||||
|
||||
}
|
@@ -1,15 +1,33 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
public class SessionEmailTokenRequestJson extends GenericTokenRequestJson {
|
||||
|
||||
private String email;
|
||||
|
||||
@Override
|
||||
public String getMedium() {
|
||||
return "email";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getValue() {
|
||||
return email;
|
||||
}
|
||||
|
@@ -1,3 +1,23 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
import com.google.i18n.phonenumbers.NumberParseException;
|
||||
@@ -11,12 +31,10 @@ public class SessionPhoneTokenRequestJson extends GenericTokenRequestJson {
|
||||
private String country;
|
||||
private String phone_number;
|
||||
|
||||
@Override
|
||||
public String getMedium() {
|
||||
return "msisdn";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getValue() {
|
||||
try {
|
||||
Phonenumber.PhoneNumber num = phoneUtil.parse(phone_number, country);
|
||||
|
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class SingeLookupReplyJson {
|
||||
|
||||
private String address;
|
||||
private String medium;
|
||||
private String mxid;
|
||||
private long not_after;
|
||||
private long not_before;
|
||||
private long ts;
|
||||
private Map<String, Map<String, String>> signatures = new HashMap<>();
|
||||
|
||||
public SingeLookupReplyJson(SingleLookupReply reply) {
|
||||
this.address = reply.getRequest().getThreePid();
|
||||
this.medium = reply.getRequest().getType();
|
||||
this.mxid = reply.getMxid().getId();
|
||||
this.not_after = reply.getNotAfter().toEpochMilli();
|
||||
this.not_before = reply.getNotBefore().toEpochMilli();
|
||||
this.ts = reply.getTimestamp().toEpochMilli();
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public String getMxid() {
|
||||
return mxid;
|
||||
}
|
||||
|
||||
public long getNot_after() {
|
||||
return not_after;
|
||||
}
|
||||
|
||||
public long getNot_before() {
|
||||
return not_before;
|
||||
}
|
||||
|
||||
public long getTs() {
|
||||
return ts;
|
||||
}
|
||||
|
||||
public boolean isSigned() {
|
||||
return signatures != null && !signatures.isEmpty();
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.io;
|
||||
|
||||
import io.kamax.mxisd.invitation.IThreePidInviteReply;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
public class ThreePidInviteReplyIO {
|
||||
|
||||
private String token;
|
||||
private List<Key> public_keys;
|
||||
private String display_name;
|
||||
|
||||
public ThreePidInviteReplyIO(IThreePidInviteReply reply, String pubKey, String publicUrl) {
|
||||
this.token = reply.getToken();
|
||||
this.public_keys = Collections.singletonList(new Key(pubKey, publicUrl));
|
||||
this.display_name = reply.getDisplayName();
|
||||
}
|
||||
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
public List<Key> getPublic_keys() {
|
||||
return public_keys;
|
||||
}
|
||||
|
||||
public String getDisplay_name() {
|
||||
return display_name;
|
||||
}
|
||||
|
||||
public class Key {
|
||||
private String key_validity_url;
|
||||
private String public_key;
|
||||
|
||||
public Key(String key, String publicUrl) {
|
||||
this.key_validity_url = publicUrl + "/_matrix/identity/api/v1/pubkey/isvalid";
|
||||
this.public_key = key;
|
||||
}
|
||||
|
||||
public String getKey_validity_url() {
|
||||
return key_validity_url;
|
||||
}
|
||||
|
||||
public String getPublic_key() {
|
||||
return public_key;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.controller.v1.remote;
|
||||
|
||||
public class RemoteIdentityAPIv1 {
|
||||
|
||||
public static final String BASE = "/_matrix/identity/remote/api/v1";
|
||||
public static final String SESSION_REQUEST_TOKEN = BASE + "/validate/requestToken";
|
||||
public static final String SESSION_CHECK = BASE + "/validate/check";
|
||||
|
||||
public static String getRequestToken(String id, String secret) {
|
||||
return SESSION_REQUEST_TOKEN + "?sid=" + id + "&client_secret=" + secret;
|
||||
}
|
||||
|
||||
public static String getSessionCheck(String id, String secret) {
|
||||
return SESSION_CHECK + "?sid=" + id + "&client_secret=" + secret;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,59 @@
|
||||
package io.kamax.mxisd.controller.v1.remote;
|
||||
|
||||
import io.kamax.mxisd.config.ViewConfig;
|
||||
import io.kamax.mxisd.exception.SessionNotValidatedException;
|
||||
import io.kamax.mxisd.session.SessionMananger;
|
||||
import io.kamax.mxisd.threepid.session.IThreePidSession;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import static io.kamax.mxisd.controller.v1.remote.RemoteIdentityAPIv1.SESSION_CHECK;
|
||||
import static io.kamax.mxisd.controller.v1.remote.RemoteIdentityAPIv1.SESSION_REQUEST_TOKEN;
|
||||
|
||||
@Controller
|
||||
public class RemoteSessionController {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(RemoteSessionController.class);
|
||||
|
||||
@Autowired
|
||||
private ViewConfig viewCfg;
|
||||
|
||||
@Autowired
|
||||
private SessionMananger mgr;
|
||||
|
||||
@RequestMapping(path = SESSION_REQUEST_TOKEN)
|
||||
public String requestToken(
|
||||
HttpServletRequest request,
|
||||
@RequestParam String sid,
|
||||
@RequestParam("client_secret") String secret,
|
||||
Model model
|
||||
) {
|
||||
log.info("Request {}: {}", request.getMethod(), request.getRequestURL());
|
||||
IThreePidSession session = mgr.createRemote(sid, secret);
|
||||
model.addAttribute("checkLink", RemoteIdentityAPIv1.getSessionCheck(session.getId(), session.getSecret()));
|
||||
return viewCfg.getSession().getRemote().getOnRequest().getSuccess();
|
||||
}
|
||||
|
||||
@RequestMapping(path = SESSION_CHECK)
|
||||
public String check(
|
||||
HttpServletRequest request,
|
||||
@RequestParam String sid,
|
||||
@RequestParam("client_secret") String secret) {
|
||||
log.info("Request {}: {}", request.getMethod(), request.getRequestURL());
|
||||
|
||||
try {
|
||||
mgr.validateRemote(sid, secret);
|
||||
return viewCfg.getSession().getRemote().getOnCheck().getSuccess();
|
||||
} catch (SessionNotValidatedException e) {
|
||||
return viewCfg.getSession().getRemote().getOnCheck().getFailure();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public class ConfigurationException extends RuntimeException {
|
||||
|
||||
private String key;
|
||||
private String detailedMsg;
|
||||
|
||||
public ConfigurationException(String key) {
|
||||
super("Invalid or empty value for configuration key " + key);
|
||||
}
|
||||
|
||||
public ConfigurationException(Throwable t) {
|
||||
super(t.getMessage(), t);
|
||||
}
|
||||
|
||||
public ConfigurationException(String key, String detailedMsg) {
|
||||
this(key);
|
||||
this.detailedMsg = detailedMsg;
|
||||
}
|
||||
|
||||
public Optional<String> getDetailedMessage() {
|
||||
return Optional.ofNullable(detailedMsg);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class InternalServerError extends MatrixException {
|
||||
|
||||
private String reference = Long.toString(Instant.now().toEpochMilli());
|
||||
private String internalReason;
|
||||
|
||||
public InternalServerError() {
|
||||
super(
|
||||
HttpStatus.SC_INTERNAL_SERVER_ERROR,
|
||||
"M_UNKNOWN",
|
||||
"An internal server error occured. If this error persists, please contact support with reference #" +
|
||||
Instant.now().toEpochMilli()
|
||||
);
|
||||
}
|
||||
|
||||
public InternalServerError(String internalReason) {
|
||||
this();
|
||||
this.internalReason = internalReason;
|
||||
}
|
||||
|
||||
public String getReference() {
|
||||
return reference;
|
||||
}
|
||||
|
||||
public String getInternalReason() {
|
||||
return internalReason;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.FORBIDDEN)
|
||||
public class InvalidCredentialsException extends RuntimeException {
|
||||
|
||||
public InvalidCredentialsException() {
|
||||
super("Supplied credentials are invalid");
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
public class InvalidResponseJsonException extends RuntimeException {
|
||||
|
||||
public InvalidResponseJsonException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
public class JsonMemberNotFoundException extends RuntimeException {
|
||||
|
||||
public JsonMemberNotFoundException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
public class MappingAlreadyExistsException extends RuntimeException {
|
||||
|
||||
public MappingAlreadyExistsException() {
|
||||
super("A mapping already exists for this 3PID");
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
public abstract class MatrixException extends MxisdException {
|
||||
|
||||
private int status;
|
||||
private String errorCode;
|
||||
private String error;
|
||||
|
||||
public MatrixException(int status, String errorCode, String error) {
|
||||
this.status = status;
|
||||
this.errorCode = errorCode;
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
public int getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public String getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
|
||||
public String getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
}
|
24
src/main/groovy/io/kamax/mxisd/exception/MxisdException.java
Normal file
24
src/main/groovy/io/kamax/mxisd/exception/MxisdException.java
Normal file
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
public class MxisdException extends RuntimeException {
|
||||
}
|
@@ -0,0 +1,32 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
public class NotAllowedException extends MatrixException {
|
||||
|
||||
public NotAllowedException(String s) {
|
||||
super(HttpStatus.SC_FORBIDDEN, "M_FORBIDDEN", s);
|
||||
}
|
||||
|
||||
}
|
@@ -24,5 +24,10 @@ import org.springframework.http.HttpStatus
|
||||
import org.springframework.web.bind.annotation.ResponseStatus
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_IMPLEMENTED)
|
||||
class NotImplementedException extends RuntimeException {
|
||||
public class NotImplementedException extends RuntimeException {
|
||||
|
||||
public NotImplementedException(String s) {
|
||||
super(s);
|
||||
}
|
||||
|
||||
}
|
||||
|
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class ObjectNotFoundException extends RuntimeException {
|
||||
|
||||
public ObjectNotFoundException(String type, String id) {
|
||||
super(type + " with ID " + id + " does not exist");
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
public class RemoteIdentityServerException extends MatrixException {
|
||||
|
||||
public RemoteIdentityServerException(String error) {
|
||||
super(HttpStatus.SC_SERVICE_UNAVAILABLE, "M_REMOTE_IS_ERROR", error);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,31 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
import org.apache.http.HttpStatus;
|
||||
|
||||
public class SessionNotValidatedException extends MatrixException {
|
||||
|
||||
public SessionNotValidatedException() {
|
||||
super(HttpStatus.SC_OK, "M_SESSION_NOT_VALIDATED", "This validation session has not yet been completed");
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.exception;
|
||||
|
||||
public class SessionUnknownException extends MatrixException {
|
||||
|
||||
public SessionUnknownException() {
|
||||
this("No valid session was found matching that sid and client secret");
|
||||
}
|
||||
|
||||
public SessionUnknownException(String error) {
|
||||
super(200, "M_NO_VALID_SESSION", error);
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.invitation;
|
||||
|
||||
import io.kamax.matrix._MatrixID;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public interface IThreePidInvite {
|
||||
|
||||
_MatrixID getSender();
|
||||
|
||||
String getMedium();
|
||||
|
||||
String getAddress();
|
||||
|
||||
String getRoomId();
|
||||
|
||||
Map<String, String> getProperties();
|
||||
|
||||
}
|
@@ -0,0 +1,33 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.invitation;
|
||||
|
||||
public interface IThreePidInviteReply {
|
||||
|
||||
String getId();
|
||||
|
||||
IThreePidInvite getInvite();
|
||||
|
||||
String getToken();
|
||||
|
||||
String getDisplayName();
|
||||
|
||||
}
|
338
src/main/groovy/io/kamax/mxisd/invitation/InvitationManager.java
Normal file
338
src/main/groovy/io/kamax/mxisd/invitation/InvitationManager.java
Normal file
@@ -0,0 +1,338 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.invitation;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import io.kamax.matrix.MatrixID;
|
||||
import io.kamax.mxisd.config.DnsOverwrite;
|
||||
import io.kamax.mxisd.config.DnsOverwriteEntry;
|
||||
import io.kamax.mxisd.exception.BadRequestException;
|
||||
import io.kamax.mxisd.exception.MappingAlreadyExistsException;
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply;
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping;
|
||||
import io.kamax.mxisd.lookup.strategy.LookupStrategy;
|
||||
import io.kamax.mxisd.notification.NotificationManager;
|
||||
import io.kamax.mxisd.signature.SignatureManager;
|
||||
import io.kamax.mxisd.storage.IStorage;
|
||||
import io.kamax.mxisd.storage.ormlite.ThreePidInviteIO;
|
||||
import org.apache.commons.io.IOUtils;
|
||||
import org.apache.commons.lang.RandomStringUtils;
|
||||
import org.apache.commons.lang.StringUtils;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.conn.ssl.NoopHostnameVerifier;
|
||||
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
|
||||
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
|
||||
import org.apache.http.entity.StringEntity;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.ssl.SSLContextBuilder;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONObject;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.xbill.DNS.*;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
import javax.net.ssl.HostnameVerifier;
|
||||
import javax.net.ssl.SSLContext;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ForkJoinPool;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Component
|
||||
public class InvitationManager {
|
||||
|
||||
private Logger log = LoggerFactory.getLogger(InvitationManager.class);
|
||||
|
||||
private Map<String, IThreePidInviteReply> invitations = new ConcurrentHashMap<>();
|
||||
|
||||
@Autowired
|
||||
private IStorage storage;
|
||||
|
||||
@Autowired
|
||||
private LookupStrategy lookupMgr;
|
||||
|
||||
@Autowired
|
||||
private SignatureManager signMgr;
|
||||
|
||||
@Autowired
|
||||
private DnsOverwrite dns;
|
||||
|
||||
private NotificationManager notifMgr;
|
||||
|
||||
private CloseableHttpClient client;
|
||||
private Gson gson;
|
||||
private Timer refreshTimer;
|
||||
|
||||
@Autowired
|
||||
public InvitationManager(NotificationManager notifMgr) {
|
||||
this.notifMgr = notifMgr;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
private void postConstruct() {
|
||||
gson = new Gson();
|
||||
|
||||
log.info("Loading saved invites");
|
||||
Collection<ThreePidInviteIO> ioList = storage.getInvites();
|
||||
ioList.forEach(io -> {
|
||||
log.info("Processing invite {}", gson.toJson(io));
|
||||
ThreePidInvite invite = new ThreePidInvite(
|
||||
new MatrixID(io.getSender()),
|
||||
io.getMedium(),
|
||||
io.getAddress(),
|
||||
io.getRoomId(),
|
||||
io.getProperties()
|
||||
);
|
||||
|
||||
ThreePidInviteReply reply = new ThreePidInviteReply(getId(invite), invite, io.getToken(), "");
|
||||
invitations.put(reply.getId(), reply);
|
||||
});
|
||||
|
||||
// FIXME export such madness into matrix-java-sdk with a nice wrapper to talk to a homeserver
|
||||
try {
|
||||
SSLContext sslContext = SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build();
|
||||
HostnameVerifier hostnameVerifier = new NoopHostnameVerifier();
|
||||
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
|
||||
client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
|
||||
} catch (Exception e) {
|
||||
// FIXME do better...
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
|
||||
log.info("Setting up invitation mapping refresh timer");
|
||||
refreshTimer = new Timer();
|
||||
refreshTimer.scheduleAtFixedRate(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
lookupMappingsForInvites();
|
||||
} catch (Throwable t) {
|
||||
log.error("Error when running background mapping refresh", t);
|
||||
}
|
||||
}
|
||||
}, 5000L, TimeUnit.MILLISECONDS.convert(1, TimeUnit.MINUTES)); // FIXME make configurable
|
||||
}
|
||||
|
||||
@PreDestroy
|
||||
private void preDestroy() {
|
||||
refreshTimer.cancel();
|
||||
ForkJoinPool.commonPool().awaitQuiescence(1, TimeUnit.MINUTES);
|
||||
}
|
||||
|
||||
private String getId(IThreePidInvite invite) {
|
||||
return invite.getSender().getDomain().toLowerCase() + invite.getMedium().toLowerCase() + invite.getAddress().toLowerCase();
|
||||
}
|
||||
|
||||
private String getIdForLog(IThreePidInviteReply reply) {
|
||||
return reply.getInvite().getSender().getId() + ":" + reply.getInvite().getRoomId() + ":" + reply.getInvite().getMedium() + ":" + reply.getInvite().getAddress();
|
||||
}
|
||||
|
||||
String getSrvRecordName(String domain) {
|
||||
return "_matrix._tcp." + domain;
|
||||
}
|
||||
|
||||
// TODO use caching mechanism
|
||||
// TODO export in matrix-java-sdk
|
||||
String findHomeserverForDomain(String domain) {
|
||||
Optional<DnsOverwriteEntry> entryOpt = dns.findHost(domain);
|
||||
if (entryOpt.isPresent()) {
|
||||
DnsOverwriteEntry entry = entryOpt.get();
|
||||
log.info("Found DNS overwrite for {} to {}", entry.getName(), entry.getTarget());
|
||||
return "https://" + entry.getTarget();
|
||||
}
|
||||
|
||||
log.debug("Performing SRV lookup for {}", domain);
|
||||
String lookupDns = getSrvRecordName(domain);
|
||||
log.info("Lookup name: {}", lookupDns);
|
||||
|
||||
try {
|
||||
List<SRVRecord> srvRecords = new ArrayList<>();
|
||||
Record[] rawRecords = new Lookup(lookupDns, Type.SRV).run();
|
||||
if (rawRecords != null && rawRecords.length > 0) {
|
||||
for (Record record : rawRecords) {
|
||||
if (Type.SRV == record.getType()) {
|
||||
srvRecords.add((SRVRecord) record);
|
||||
} else {
|
||||
log.info("Got non-SRV record: {}", record.toString());
|
||||
}
|
||||
}
|
||||
|
||||
srvRecords.sort(Comparator.comparingInt(SRVRecord::getPriority));
|
||||
for (SRVRecord record : srvRecords) {
|
||||
log.info("Found SRV record: {}", record.toString());
|
||||
return "https://" + record.getTarget().toString(true) + ":" + record.getPort();
|
||||
}
|
||||
} else {
|
||||
log.info("No SRV record for {}", lookupDns);
|
||||
}
|
||||
} catch (TextParseException e) {
|
||||
log.warn("Unable to perform DNS SRV query for {}: {}", lookupDns, e.getMessage());
|
||||
}
|
||||
|
||||
log.info("Performing basic lookup using domain name {}", domain);
|
||||
return "https://" + domain + ":8448";
|
||||
}
|
||||
|
||||
public synchronized IThreePidInviteReply storeInvite(IThreePidInvite invitation) { // TODO better sync
|
||||
if (!notifMgr.isMediumSupported(invitation.getMedium())) {
|
||||
throw new BadRequestException("Medium type " + invitation.getMedium() + " is not supported");
|
||||
}
|
||||
|
||||
String invId = getId(invitation);
|
||||
log.info("Handling invite for {}:{} from {} in room {}", invitation.getMedium(), invitation.getAddress(), invitation.getSender(), invitation.getRoomId());
|
||||
if (invitations.containsKey(invId)) {
|
||||
log.info("Invite is already pending for {}:{}, returning data", invitation.getMedium(), invitation.getAddress());
|
||||
return invitations.get(invId);
|
||||
}
|
||||
|
||||
Optional<?> result = lookupMgr.find(invitation.getMedium(), invitation.getAddress(), true);
|
||||
if (result.isPresent()) {
|
||||
log.info("Mapping for {}:{} already exists, refusing to store invite", invitation.getMedium(), invitation.getAddress());
|
||||
throw new MappingAlreadyExistsException();
|
||||
}
|
||||
|
||||
String token = RandomStringUtils.randomAlphanumeric(64);
|
||||
String displayName = invitation.getAddress().substring(0, 3) + "...";
|
||||
|
||||
IThreePidInviteReply reply = new ThreePidInviteReply(invId, invitation, token, displayName);
|
||||
|
||||
log.info("Performing invite to {}:{}", invitation.getMedium(), invitation.getAddress());
|
||||
notifMgr.sendForInvite(reply);
|
||||
|
||||
log.info("Storing invite under ID {}", invId);
|
||||
storage.insertInvite(reply);
|
||||
invitations.put(invId, reply);
|
||||
log.info("A new invite has been created for {}:{} on HS {}", invitation.getMedium(), invitation.getAddress(), invitation.getSender().getDomain());
|
||||
|
||||
return reply;
|
||||
}
|
||||
|
||||
public void lookupMappingsForInvites() {
|
||||
if (!invitations.isEmpty()) {
|
||||
log.info("Checking for existing mapping for pending invites");
|
||||
for (IThreePidInviteReply reply : invitations.values()) {
|
||||
log.info("Processing invite {}", getIdForLog(reply));
|
||||
ForkJoinPool.commonPool().submit(new MappingChecker(reply));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void publishMappingIfInvited(ThreePidMapping threePid) {
|
||||
log.info("Looking up possible pending invites for {}:{}", threePid.getMedium(), threePid.getValue());
|
||||
for (IThreePidInviteReply reply : invitations.values()) {
|
||||
if (StringUtils.equalsIgnoreCase(reply.getInvite().getMedium(), threePid.getMedium()) && StringUtils.equalsIgnoreCase(reply.getInvite().getAddress(), threePid.getValue())) {
|
||||
log.info("{}:{} has an invite pending on HS {}, publishing mapping", threePid.getMedium(), threePid.getValue(), reply.getInvite().getSender().getDomain());
|
||||
publishMapping(reply, threePid.getMxid());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void publishMapping(IThreePidInviteReply reply, String mxid) {
|
||||
String medium = reply.getInvite().getMedium();
|
||||
String address = reply.getInvite().getAddress();
|
||||
String domain = reply.getInvite().getSender().getDomain();
|
||||
log.info("Discovering HS for domain {}", domain);
|
||||
String hsUrlOpt = findHomeserverForDomain(domain);
|
||||
|
||||
// TODO this is needed as this will block if called during authentication cycle due to synapse implementation
|
||||
new Thread(() -> { // FIXME need to make this retry-able and within a general background working pool
|
||||
HttpPost req = new HttpPost(hsUrlOpt + "/_matrix/federation/v1/3pid/onbind");
|
||||
// Expected body: https://matrix.to/#/!HUeDbmFUsWAhxHHvFG:matrix.org/$150469846739DCLWc:matrix.trancendances.fr
|
||||
JSONObject obj = new JSONObject(); // TODO use Gson instead
|
||||
obj.put("mxid", mxid);
|
||||
obj.put("token", reply.getToken());
|
||||
obj.put("signatures", signMgr.signMessageJson(obj.toString()));
|
||||
|
||||
JSONObject objUp = new JSONObject();
|
||||
objUp.put("mxid", mxid);
|
||||
objUp.put("medium", medium);
|
||||
objUp.put("address", address);
|
||||
objUp.put("sender", reply.getInvite().getSender().getId());
|
||||
objUp.put("room_id", reply.getInvite().getRoomId());
|
||||
objUp.put("signed", obj);
|
||||
|
||||
JSONObject content = new JSONObject(); // TODO use Gson instead
|
||||
JSONArray invites = new JSONArray();
|
||||
invites.put(objUp);
|
||||
content.put("invites", invites);
|
||||
content.put("medium", medium);
|
||||
content.put("address", address);
|
||||
content.put("mxid", mxid);
|
||||
|
||||
content.put("signatures", signMgr.signMessageJson(content.toString()));
|
||||
|
||||
StringEntity entity = new StringEntity(content.toString(), StandardCharsets.UTF_8);
|
||||
entity.setContentType("application/json");
|
||||
req.setEntity(entity);
|
||||
try {
|
||||
log.info("Posting onBind event to {}", req.getURI());
|
||||
CloseableHttpResponse response = client.execute(req);
|
||||
int statusCode = response.getStatusLine().getStatusCode();
|
||||
log.info("Answer code: {}", statusCode);
|
||||
if (statusCode >= 300) {
|
||||
log.warn("Answer body: {}", IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8));
|
||||
} else {
|
||||
invitations.remove(getId(reply.getInvite()));
|
||||
storage.deleteInvite(reply.getId());
|
||||
log.info("Removed invite from internal store");
|
||||
}
|
||||
response.close();
|
||||
} catch (IOException e) {
|
||||
log.warn("Unable to tell HS {} about invite being mapped", domain, e);
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
private class MappingChecker implements Runnable {
|
||||
|
||||
private IThreePidInviteReply reply;
|
||||
|
||||
public MappingChecker(IThreePidInviteReply reply) {
|
||||
this.reply = reply;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
log.info("Searching for mapping created since invite {} was created", getIdForLog(reply));
|
||||
Optional<SingleLookupReply> result = lookupMgr.find(reply.getInvite().getMedium(), reply.getInvite().getAddress(), true);
|
||||
if (result.isPresent()) {
|
||||
SingleLookupReply lookup = result.get();
|
||||
log.info("Found mapping for pending invite {}", getIdForLog(reply));
|
||||
publishMapping(reply, lookup.getMxid().getId());
|
||||
} else {
|
||||
log.info("No mapping for pending invite {}", getIdForLog(reply));
|
||||
}
|
||||
} catch (Throwable t) {
|
||||
log.error("Unable to process invite", t);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.invitation;
|
||||
|
||||
import io.kamax.matrix._MatrixID;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
public class ThreePidInvite implements IThreePidInvite {
|
||||
|
||||
private _MatrixID sender;
|
||||
private String medium;
|
||||
private String address;
|
||||
private String roomId;
|
||||
private Map<String, String> properties;
|
||||
|
||||
public ThreePidInvite(_MatrixID sender, String medium, String address, String roomId) {
|
||||
this.sender = sender;
|
||||
this.medium = medium;
|
||||
this.address = address;
|
||||
this.roomId = roomId;
|
||||
this.properties = new HashMap<>();
|
||||
}
|
||||
|
||||
public ThreePidInvite(_MatrixID sender, String medium, String address, String roomId, Map<String, String> properties) {
|
||||
this(sender, medium, address, roomId);
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public _MatrixID getSender() {
|
||||
return sender;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getRoomId() {
|
||||
return roomId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, String> getProperties() {
|
||||
return properties;
|
||||
}
|
||||
|
||||
}
|
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.invitation;
|
||||
|
||||
public class ThreePidInviteReply implements IThreePidInviteReply {
|
||||
|
||||
private String id;
|
||||
private IThreePidInvite invite;
|
||||
private String token;
|
||||
private String displayName;
|
||||
|
||||
public ThreePidInviteReply(String id, IThreePidInvite invite, String token, String displayName) {
|
||||
this.id = id;
|
||||
this.invite = invite;
|
||||
this.token = token;
|
||||
this.displayName = displayName;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public IThreePidInvite getInvite() {
|
||||
return invite;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getToken() {
|
||||
return token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getDisplayName() {
|
||||
return displayName;
|
||||
}
|
||||
|
||||
}
|
@@ -20,9 +20,23 @@
|
||||
|
||||
package io.kamax.mxisd.lookup;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public abstract class ALookupRequest {
|
||||
|
||||
private String id;
|
||||
private String requester;
|
||||
private String userAgent;
|
||||
private boolean isRecursive;
|
||||
private List<String> recurseHosts;
|
||||
|
||||
public String getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getRequester() {
|
||||
return requester;
|
||||
@@ -32,4 +46,28 @@ public abstract class ALookupRequest {
|
||||
this.requester = requester;
|
||||
}
|
||||
|
||||
public String getUserAgent() {
|
||||
return userAgent;
|
||||
}
|
||||
|
||||
public void setUserAgent(String userAgent) {
|
||||
this.userAgent = userAgent;
|
||||
}
|
||||
|
||||
public boolean isRecursive() {
|
||||
return isRecursive;
|
||||
}
|
||||
|
||||
public void setRecursive(boolean recursive) {
|
||||
isRecursive = recursive;
|
||||
}
|
||||
|
||||
public List<String> getRecurseHosts() {
|
||||
return recurseHosts;
|
||||
}
|
||||
|
||||
public void setRecurseHosts(List<String> recurseHosts) {
|
||||
this.recurseHosts = recurseHosts;
|
||||
}
|
||||
|
||||
}
|
||||
|
116
src/main/groovy/io/kamax/mxisd/lookup/SingleLookupReply.java
Normal file
116
src/main/groovy/io/kamax/mxisd/lookup/SingleLookupReply.java
Normal file
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.lookup;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.JsonSyntaxException;
|
||||
import io.kamax.matrix.MatrixID;
|
||||
import io.kamax.matrix._MatrixID;
|
||||
import io.kamax.mxisd.controller.v1.io.SingeLookupReplyJson;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class SingleLookupReply {
|
||||
|
||||
private static Gson gson = new Gson();
|
||||
|
||||
private boolean isRecursive;
|
||||
private boolean isSigned;
|
||||
private String body;
|
||||
private SingleLookupRequest request;
|
||||
private _MatrixID mxid;
|
||||
private Instant notBefore;
|
||||
private Instant notAfter;
|
||||
private Instant timestamp;
|
||||
|
||||
public static SingleLookupReply fromRecursive(SingleLookupRequest request, String body) {
|
||||
SingleLookupReply reply = new SingleLookupReply();
|
||||
reply.isRecursive = true;
|
||||
reply.request = request;
|
||||
reply.body = body;
|
||||
|
||||
try {
|
||||
SingeLookupReplyJson json = gson.fromJson(body, SingeLookupReplyJson.class);
|
||||
reply.mxid = new MatrixID(json.getMxid());
|
||||
reply.notAfter = Instant.ofEpochMilli(json.getNot_after());
|
||||
reply.notBefore = Instant.ofEpochMilli(json.getNot_before());
|
||||
reply.timestamp = Instant.ofEpochMilli(json.getTs());
|
||||
reply.isSigned = json.isSigned();
|
||||
} catch (JsonSyntaxException e) {
|
||||
// stub - we only want to try, nothing more
|
||||
}
|
||||
|
||||
return reply;
|
||||
}
|
||||
|
||||
private SingleLookupReply() {
|
||||
// stub
|
||||
}
|
||||
|
||||
public SingleLookupReply(SingleLookupRequest request, String mxid) {
|
||||
this(request, new MatrixID(mxid));
|
||||
}
|
||||
|
||||
public SingleLookupReply(SingleLookupRequest request, _MatrixID mxid) {
|
||||
this(request, mxid, Instant.now(), Instant.ofEpochMilli(0), Instant.ofEpochMilli(253402300799000L));
|
||||
}
|
||||
|
||||
public SingleLookupReply(SingleLookupRequest request, _MatrixID mxid, Instant timestamp, Instant notBefore, Instant notAfter) {
|
||||
this.request = request;
|
||||
this.mxid = mxid;
|
||||
this.timestamp = timestamp;
|
||||
this.notBefore = notBefore;
|
||||
this.notAfter = notAfter;
|
||||
}
|
||||
|
||||
public boolean isRecursive() {
|
||||
return isRecursive;
|
||||
}
|
||||
|
||||
public boolean isSigned() {
|
||||
return isSigned;
|
||||
}
|
||||
|
||||
public String getBody() {
|
||||
return body;
|
||||
}
|
||||
|
||||
public SingleLookupRequest getRequest() {
|
||||
return request;
|
||||
}
|
||||
|
||||
public _MatrixID getMxid() {
|
||||
return mxid;
|
||||
}
|
||||
|
||||
public Instant getNotBefore() {
|
||||
return notBefore;
|
||||
}
|
||||
|
||||
public Instant getNotAfter() {
|
||||
return notAfter;
|
||||
}
|
||||
|
||||
public Instant getTimestamp() {
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
}
|
@@ -1,29 +0,0 @@
|
||||
package io.kamax.mxisd.lookup;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class ThreePid {
|
||||
|
||||
private String medium;
|
||||
private String address;
|
||||
private Instant validation;
|
||||
|
||||
public ThreePid(String medium, String address, Instant validation) {
|
||||
this.medium = medium;
|
||||
this.address = address;
|
||||
this.validation = validation;
|
||||
}
|
||||
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
||||
public String getAddress() {
|
||||
return address;
|
||||
}
|
||||
|
||||
public Instant getValidation() {
|
||||
return validation;
|
||||
}
|
||||
|
||||
}
|
@@ -21,6 +21,7 @@
|
||||
package io.kamax.mxisd.lookup;
|
||||
|
||||
import groovy.json.JsonOutput;
|
||||
import io.kamax.mxisd.ThreePid;
|
||||
|
||||
public class ThreePidMapping {
|
||||
|
||||
@@ -28,6 +29,20 @@ public class ThreePidMapping {
|
||||
private String value;
|
||||
private String mxid;
|
||||
|
||||
public ThreePidMapping() {
|
||||
// stub
|
||||
}
|
||||
|
||||
public ThreePidMapping(ThreePid threePid, String mxid) {
|
||||
this(threePid.getMedium(), threePid.getAddress(), mxid);
|
||||
}
|
||||
|
||||
public ThreePidMapping(String medium, String value, String mxid) {
|
||||
setMedium(medium);
|
||||
setValue(value);
|
||||
setMxid(mxid);
|
||||
}
|
||||
|
||||
public String getMedium() {
|
||||
return medium;
|
||||
}
|
||||
|
@@ -0,0 +1,40 @@
|
||||
/*
|
||||
* mxisd - Matrix Identity Server Daemon
|
||||
* Copyright (C) 2017 Maxime Dor
|
||||
*
|
||||
* https://max.kamax.io/
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package io.kamax.mxisd.lookup;
|
||||
|
||||
import io.kamax.mxisd.ThreePid;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public class ThreePidValidation extends ThreePid {
|
||||
|
||||
private Instant validation;
|
||||
|
||||
public ThreePidValidation(ThreePid tpid, Instant validation) {
|
||||
super(tpid);
|
||||
this.validation = validation;
|
||||
}
|
||||
|
||||
public Instant getValidation() {
|
||||
return validation;
|
||||
}
|
||||
|
||||
}
|
@@ -20,12 +20,13 @@
|
||||
|
||||
package io.kamax.mxisd.lookup.fetcher
|
||||
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping
|
||||
|
||||
interface IBridgeFetcher {
|
||||
|
||||
Optional<?> find(SingleLookupRequest request)
|
||||
Optional<SingleLookupReply> find(SingleLookupRequest request)
|
||||
|
||||
List<ThreePidMapping> populate(List<ThreePidMapping> mappings)
|
||||
|
||||
|
@@ -20,13 +20,15 @@
|
||||
|
||||
package io.kamax.mxisd.lookup.fetcher
|
||||
|
||||
import io.kamax.mxisd.lookup.SingleLookupReply
|
||||
import io.kamax.mxisd.lookup.SingleLookupRequest
|
||||
import io.kamax.mxisd.lookup.ThreePidMapping
|
||||
|
||||
interface IRemoteIdentityServerFetcher {
|
||||
|
||||
boolean isUsable(String remote)
|
||||
|
||||
Optional<?> find(String remote, String type, String threePid)
|
||||
Optional<SingleLookupReply> find(String remote, SingleLookupRequest request)
|
||||
|
||||
List<ThreePidMapping> find(String remote, List<ThreePidMapping> mappings)
|
||||
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user