Start structural port from Spring Boot to Undertow

This commit is contained in:
Max Dor
2018-12-25 05:32:00 +01:00
parent df44428a85
commit 05493da27c
195 changed files with 3313 additions and 2079 deletions

1
.gitignore vendored
View File

@@ -8,6 +8,7 @@ out/
# Local dev config # Local dev config
/application.yaml /application.yaml
/mxisd.yaml
# Local dev storage # Local dev storage
/mxisd.db /mxisd.db

View File

@@ -21,7 +21,9 @@
import java.util.regex.Pattern import java.util.regex.Pattern
apply plugin: 'java' apply plugin: 'java'
apply plugin: 'org.springframework.boot' apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'
apply plugin: 'idea'
def confFileName = "application.example.yaml" def confFileName = "application.example.yaml"
def distDir = "${project.buildDir}/dist" def distDir = "${project.buildDir}/dist"
@@ -43,6 +45,9 @@ def debBuildSystemdPath = "${debBuildBasePath}${debSystemdPath}"
def dockerImageName = "kamax/mxisd" def dockerImageName = "kamax/mxisd"
def dockerImageTag = "${dockerImageName}:${mxisdVersion()}" def dockerImageTag = "${dockerImageName}:${mxisdVersion()}"
group = 'io.kamax'
mainClassName = 'io.kamax.mxisd.MxisdStandaloneExec'
String mxisdVersion() { String mxisdVersion() {
def versionPattern = Pattern.compile("v(\\d+\\.)?(\\d+\\.)?(\\d+)(-.*)?") def versionPattern = Pattern.compile("v(\\d+\\.)?(\\d+\\.)?(\\d+)(-.*)?")
@@ -64,16 +69,16 @@ String gitVersion() {
buildscript { buildscript {
repositories { repositories {
mavenCentral() jcenter()
} }
dependencies { dependencies {
classpath 'org.springframework.boot:spring-boot-gradle-plugin:1.5.3.RELEASE' classpath 'com.github.jengelman.gradle.plugins:shadow:4.0.3'
} }
} }
repositories { repositories {
mavenCentral() jcenter()
maven { url "https://kamax.io/maven/releases/" } maven { url "https://kamax.io/maven/releases/" }
maven { url "https://kamax.io/maven/snapshots/" } maven { url "https://kamax.io/maven/snapshots/" }
} }
@@ -81,12 +86,9 @@ repositories {
dependencies { dependencies {
// Easy file management // Easy file management
compile 'commons-io:commons-io:2.5' compile 'commons-io:commons-io:2.5'
// Spring Boot - standalone app // Config management
compile 'org.springframework.boot:spring-boot-starter-web:1.5.10.RELEASE' compile 'org.yaml:snakeyaml:1.23'
// Thymeleaf for HTML templates
compile "org.springframework.boot:spring-boot-starter-thymeleaf:1.5.10.RELEASE"
// Matrix Java SDK // Matrix Java SDK
compile 'io.kamax:matrix-java-sdk:0.0.14-8-g0e57ec6' compile 'io.kamax:matrix-java-sdk:0.0.14-8-g0e57ec6'
@@ -137,17 +139,18 @@ dependencies {
// ZT-Exec for exec identity store // ZT-Exec for exec identity store
compile 'org.zeroturnaround:zt-exec:1.10' compile 'org.zeroturnaround:zt-exec:1.10'
// HTTP server
compile 'io.undertow:undertow-core:2.0.16.Final'
testCompile 'junit:junit:4.12' testCompile 'junit:junit:4.12'
testCompile 'com.github.tomakehurst:wiremock:2.8.0' testCompile 'com.github.tomakehurst:wiremock:2.8.0'
testCompile 'com.unboundid:unboundid-ldapsdk:4.0.9' testCompile 'com.unboundid:unboundid-ldapsdk:4.0.9'
} }
springBoot { shadowJar {
executable = true baseName = project.name
classifier = null
embeddedLaunchScriptProperties = [ version = null
confFolder: "/etc/default"
]
} }
processResources { processResources {

View File

@@ -0,0 +1,193 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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 io.kamax.matrix.crypto.KeyManager;
import io.kamax.matrix.crypto.SignatureManager;
import io.kamax.mxisd.as.AppSvcManager;
import io.kamax.mxisd.auth.AuthManager;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.backend.sql.synapse.Synapse;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryManager;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.dns.ClientDnsOverwrite;
import io.kamax.mxisd.dns.FederationDnsOverwrite;
import io.kamax.mxisd.http.undertow.handler.SaneHandler;
import io.kamax.mxisd.http.undertow.handler.as.v1.AsNotFoundHandler;
import io.kamax.mxisd.http.undertow.handler.as.v1.AsTransactionHandler;
import io.kamax.mxisd.http.undertow.handler.auth.RestAuthHandler;
import io.kamax.mxisd.http.undertow.handler.auth.v1.LoginGetHandler;
import io.kamax.mxisd.http.undertow.handler.auth.v1.LoginHandler;
import io.kamax.mxisd.http.undertow.handler.auth.v1.LoginPostHandler;
import io.kamax.mxisd.http.undertow.handler.directory.v1.UserDirectorySearchHandler;
import io.kamax.mxisd.http.undertow.handler.identity.v1.*;
import io.kamax.mxisd.http.undertow.handler.profile.v1.InternalProfileHandler;
import io.kamax.mxisd.http.undertow.handler.profile.v1.ProfileHandler;
import io.kamax.mxisd.http.undertow.handler.status.StatusHandler;
import io.kamax.mxisd.invitation.InvitationManager;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.lookup.provider.BridgeFetcher;
import io.kamax.mxisd.lookup.provider.RemoteIdentityServerFetcher;
import io.kamax.mxisd.lookup.strategy.LookupStrategy;
import io.kamax.mxisd.lookup.strategy.RecursivePriorityLookupStrategy;
import io.kamax.mxisd.notification.NotificationHandlers;
import io.kamax.mxisd.notification.NotificationManager;
import io.kamax.mxisd.profile.ProfileManager;
import io.kamax.mxisd.profile.ProfileProviders;
import io.kamax.mxisd.session.SessionMananger;
import io.kamax.mxisd.spring.CryptoFactory;
import io.kamax.mxisd.storage.ormlite.OrmLiteSqliteStorage;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.util.ServiceLoader;
public class Mxisd {
private MxisdConfig cfg;
private CloseableHttpClient httpClient;
private KeyManager keyMgr;
private SignatureManager signMgr;
// Features
private AuthManager authMgr;
private DirectoryManager dirMgr;
private LookupStrategy idStrategy;
private InvitationManager invMgr;
private ProfileManager pMgr;
private AppSvcManager asHander;
private SessionMananger sessMgr;
// I/O
private Undertow httpSrv;
public Mxisd(MxisdConfig cfg) {
this.cfg = cfg.build();
}
private void build() {
httpClient = HttpClients.custom()
.setUserAgent("mxisd")
.setMaxConnPerRoute(Integer.MAX_VALUE)
.setMaxConnTotal(Integer.MAX_VALUE)
.build();
OrmLiteSqliteStorage storage = new OrmLiteSqliteStorage(cfg);
keyMgr = CryptoFactory.getKeyManager(cfg.getKey());
signMgr = CryptoFactory.getSignatureManager(keyMgr, cfg.getServer());
ClientDnsOverwrite clientDns = new ClientDnsOverwrite(cfg.getDns().getOverwrite());
FederationDnsOverwrite fedDns = new FederationDnsOverwrite(cfg.getDns().getOverwrite());
pMgr = new ProfileManager(ProfileProviders.get(), clientDns, httpClient);
NotificationManager notifMgr = new NotificationManager(cfg.getNotification(), NotificationHandlers.get());
Synapse synapse = new Synapse(cfg.getSynapseSql());
RemoteIdentityServerFetcher srvFetcher = new RemoteIdentityServerFetcher(httpClient);
BridgeFetcher bridgeFetcher = new BridgeFetcher(cfg.getLookup().getRecursive().getBridge(), srvFetcher);
idStrategy = new RecursivePriorityLookupStrategy(cfg.getLookup(), ThreePidProviders.get(), bridgeFetcher);
invMgr = new InvitationManager(cfg.getInvite(), storage, idStrategy, signMgr, fedDns, notifMgr);
sessMgr = new SessionMananger(cfg.getSession(), cfg.getMatrix(), storage, notifMgr, httpClient);
authMgr = new AuthManager(cfg, AuthProviders.get(), idStrategy, invMgr, clientDns, httpClient);
dirMgr = new DirectoryManager(cfg.getDirectory(), clientDns, httpClient, DirectoryProviders.get());
asHander = new AppSvcManager(cfg, storage, pMgr, notifMgr, synapse);
ServiceLoader.load(IdentityStoreSupplier.class).iterator().forEachRemaining(p -> p.accept(this));
}
public MxisdConfig getConfig() {
return cfg;
}
public CloseableHttpClient getHttpClient() {
return httpClient;
}
public InvitationManager getInvitationManager() {
return invMgr;
}
public void start() {
build();
HttpHandler asNotFoundHandler = SaneHandler.around(new AsNotFoundHandler(asHander));
HttpHandler asTxnHandler = SaneHandler.around(new AsTransactionHandler(asHander));
HttpHandler storeInvHandler = SaneHandler.around(new StoreInviteHandler(cfg.getServer(), invMgr, keyMgr));
HttpHandler sessValidateHandler = SaneHandler.around(new SessionValidateHandler(sessMgr, cfg.getServer(), cfg.getView()));
httpSrv = Undertow.builder().addHttpListener(cfg.getServer().getPort(), "0.0.0.0").setHandler(Handlers.routing()
// Status endpoints
.get(StatusHandler.Path, SaneHandler.around(new StatusHandler()))
// Authentication endpoints
.get(LoginHandler.Path, SaneHandler.around(new LoginGetHandler(authMgr, httpClient)))
.post(LoginHandler.Path, SaneHandler.around(new LoginPostHandler(authMgr)))
.post(RestAuthHandler.Path, SaneHandler.around(new RestAuthHandler(authMgr)))
// Directory endpoints
.post(UserDirectorySearchHandler.Path, SaneHandler.around(new UserDirectorySearchHandler(dirMgr)))
// Key endpoints
.get(KeyGetHandler.Path, SaneHandler.around(new KeyGetHandler(keyMgr)))
.get(RegularKeyIsValidHandler.Path, SaneHandler.around(new RegularKeyIsValidHandler(keyMgr)))
.get(EphemeralKeyIsValidHandler.Path, SaneHandler.around(new EphemeralKeyIsValidHandler()))
// Identity endpoints
.get(HelloHandler.Path, new HelloHandler())
.get(SingleLookupHandler.Path, new SingleLookupHandler(idStrategy, signMgr))
.post(BulkLookupHandler.Path, new BulkLookupHandler(idStrategy))
.post(StoreInviteHandler.Path, storeInvHandler)
.post(SessionStartHandler.Path, SaneHandler.around(new SessionStartHandler(sessMgr)))
.get(SessionValidateHandler.Path, sessValidateHandler)
.post(SessionValidateHandler.Path, sessValidateHandler)
.get(SessionTpidGetValidatedHandler.Path, SaneHandler.around(new SessionTpidGetValidatedHandler(sessMgr)))
.post(SessionTpidBindHandler.Path, SaneHandler.around(new SessionTpidBindHandler(sessMgr, invMgr)))
.get(RemoteIdentityAPIv1.SESSION_REQUEST_TOKEN, SaneHandler.around(new RemoteSessionStartHandler(sessMgr, cfg.getView())))
.get(RemoteIdentityAPIv1.SESSION_CHECK, SaneHandler.around(new RemoteSessionCheckHandler(sessMgr, cfg.getView())))
// Profile endpoints
.get(ProfileHandler.Path, SaneHandler.around(new ProfileHandler(pMgr)))
.get(InternalProfileHandler.Path, SaneHandler.around(new InternalProfileHandler(pMgr)))
// Application Service endpoints
.get("/_matrix/app/v1/users/**", asNotFoundHandler)
.get("/users/**", asNotFoundHandler) // Legacy endpoint
.get("/_matrix/app/v1/rooms/**", asNotFoundHandler)
.get("/rooms/**", asNotFoundHandler) // Legacy endpoint
.put(AsTransactionHandler.Path, asTxnHandler)
.put("/transactions/{" + AsTransactionHandler.ID + "}", asTxnHandler) // Legacy endpoint
).build();
httpSrv.start();
}
public void stop() {
httpSrv.stop();
}
}

View File

@@ -18,21 +18,18 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package io.kamax.mxisd.controller; package io.kamax.mxisd;
import org.springframework.http.MediaType; import io.kamax.mxisd.config.MxisdConfig;
import org.springframework.web.bind.annotation.CrossOrigin; import io.kamax.mxisd.config.YamlConfigLoader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController import java.io.IOException;
@CrossOrigin
@RequestMapping(produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class PingController {
@RequestMapping(value = "/_matrix/identity/api/v1") public class MxisdStandaloneExec {
public String ping() {
return "{}"; public static void main(String[] args) throws IOException {
MxisdConfig cfg = YamlConfigLoader.loadFromFile("mxisd.yaml"); // FIXME no hardcoding, make it configurable via Build, Env and CLI parameters
new Mxisd(cfg).start();
} }
} }

View File

@@ -28,8 +28,10 @@ import io.kamax.matrix._ThreePid;
import io.kamax.matrix.event.EventKey; import io.kamax.matrix.event.EventKey;
import io.kamax.matrix.json.GsonUtil; import io.kamax.matrix.json.GsonUtil;
import io.kamax.mxisd.backend.sql.synapse.Synapse; import io.kamax.mxisd.backend.sql.synapse.Synapse;
import io.kamax.mxisd.config.ListenerConfig;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.exception.HttpMatrixException;
import io.kamax.mxisd.exception.NotAllowedException;
import io.kamax.mxisd.notification.NotificationManager; import io.kamax.mxisd.notification.NotificationManager;
import io.kamax.mxisd.profile.ProfileManager; import io.kamax.mxisd.profile.ProfileManager;
import io.kamax.mxisd.storage.IStorage; import io.kamax.mxisd.storage.IStorage;
@@ -38,8 +40,6 @@ import io.kamax.mxisd.util.GsonParser;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.InputStream; import java.io.InputStream;
import java.time.Instant; import java.time.Instant;
@@ -48,14 +48,12 @@ import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Component public class AppSvcManager {
public class AppServiceHandler {
private final Logger log = LoggerFactory.getLogger(AppServiceHandler.class); private transient final Logger log = LoggerFactory.getLogger(AppSvcManager.class);
private final GsonParser parser; private final GsonParser parser;
private String localpart;
private MatrixConfig cfg; private MatrixConfig cfg;
private IStorage store; private IStorage store;
private ProfileManager profiler; private ProfileManager profiler;
@@ -64,22 +62,36 @@ public class AppServiceHandler {
private Map<String, CompletableFuture<String>> transactionsInProgress; private Map<String, CompletableFuture<String>> transactionsInProgress;
@Autowired public AppSvcManager(MxisdConfig cfg, IStorage store, ProfileManager profiler, NotificationManager notif, Synapse synapse) {
public AppServiceHandler(ListenerConfig lCfg, MatrixConfig cfg, IStorage store, ProfileManager profiler, NotificationManager notif, Synapse synapse) { this.cfg = cfg.getMatrix();
this.cfg = cfg;
this.store = store; this.store = store;
this.profiler = profiler; this.profiler = profiler;
this.notif = notif; this.notif = notif;
this.synapse = synapse; this.synapse = synapse;
localpart = lCfg.getLocalpart();
parser = new GsonParser(); parser = new GsonParser();
transactionsInProgress = new ConcurrentHashMap<>(); transactionsInProgress = new ConcurrentHashMap<>();
} }
public AppSvcManager withToken(String token) {
if (StringUtils.isBlank(token)) {
throw new HttpMatrixException(401, "M_UNAUTHORIZED", "No HS token");
}
if (!StringUtils.equals(cfg.getListener().getToken().getHs(), token)) {
throw new NotAllowedException("Invalid HS token");
}
return this;
}
public CompletableFuture<String> processTransaction(String txnId, InputStream is) { public CompletableFuture<String> processTransaction(String txnId, InputStream is) {
if (StringUtils.isEmpty(txnId)) {
throw new IllegalArgumentException("Transaction ID cannot be empty");
}
synchronized (this) { synchronized (this) {
Optional<ASTransactionDao> dao = store.getTransactionResult(localpart, txnId); Optional<ASTransactionDao> dao = store.getTransactionResult(cfg.getListener().getLocalpart(), txnId);
if (dao.isPresent()) { if (dao.isPresent()) {
log.info("AS Transaction {} already processed - returning computed result", txnId); log.info("AS Transaction {} already processed - returning computed result", txnId);
return CompletableFuture.completedFuture(dao.get().getResult()); return CompletableFuture.completedFuture(dao.get().getResult());
@@ -104,19 +116,19 @@ public class AppServiceHandler {
log.debug("{} event(s) parsed", events.size()); log.debug("{} event(s) parsed", events.size());
processTransaction(events); processTransaction(events);
Instant end = Instant.now();
log.info("Processed AS transaction {} in {} ms", txnId, (Instant.now().toEpochMilli() - start.toEpochMilli()));
Instant end = Instant.now();
String result = "{}"; String result = "{}";
try { try {
log.info("Saving transaction details to store"); log.info("Saving transaction details to store");
store.insertTransactionResult(localpart, txnId, end, result); store.insertTransactionResult(cfg.getListener().getLocalpart(), txnId, end, result);
} finally { } finally {
log.debug("Removing CompletedFuture from transaction map"); log.debug("Removing CompletedFuture from transaction map");
transactionsInProgress.remove(txnId); transactionsInProgress.remove(txnId);
} }
log.info("Processed AS transaction {} in {} ms", txnId, (Instant.now().toEpochMilli() - start.toEpochMilli()));
future.complete(result); future.complete(result);
} catch (Exception e) { } catch (Exception e) {
log.error("Unable to properly process transaction {}", txnId, e); log.error("Unable to properly process transaction {}", txnId, e);

View File

@@ -37,6 +37,7 @@ import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
import io.kamax.mxisd.auth.provider.BackendAuthResult; import io.kamax.mxisd.auth.provider.BackendAuthResult;
import io.kamax.mxisd.config.AuthenticationConfig; import io.kamax.mxisd.config.AuthenticationConfig;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.dns.ClientDnsOverwrite; import io.kamax.mxisd.dns.ClientDnsOverwrite;
import io.kamax.mxisd.exception.RemoteLoginException; import io.kamax.mxisd.exception.RemoteLoginException;
import io.kamax.mxisd.invitation.InvitationManager; import io.kamax.mxisd.invitation.InvitationManager;
@@ -53,8 +54,6 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.IOException; import java.io.IOException;
import java.net.URI; import java.net.URI;
@@ -63,7 +62,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@Service
public class AuthManager { public class AuthManager {
private static final String TypeKey = "type"; private static final String TypeKey = "type";
@@ -74,8 +72,8 @@ public class AuthManager {
private static final String UserIdTypeValue = "m.id.user"; private static final String UserIdTypeValue = "m.id.user";
private static final String ThreepidTypeValue = "m.id.thirdparty"; private static final String ThreepidTypeValue = "m.id.thirdparty";
private final Logger log = LoggerFactory.getLogger(AuthManager.class); private transient final Logger log = LoggerFactory.getLogger(AuthManager.class);
private final Gson gson = GsonUtil.get(); private final Gson gson = GsonUtil.get(); // FIXME replace
private List<AuthenticatorProvider> providers; private List<AuthenticatorProvider> providers;
private MatrixConfig mxCfg; private MatrixConfig mxCfg;
@@ -85,18 +83,16 @@ public class AuthManager {
private LookupStrategy strategy; private LookupStrategy strategy;
private CloseableHttpClient client; private CloseableHttpClient client;
@Autowired
public AuthManager( public AuthManager(
AuthenticationConfig cfg, MxisdConfig cfg,
MatrixConfig mxCfg, List<? extends AuthenticatorProvider> providers,
List<AuthenticatorProvider> providers,
LookupStrategy strategy, LookupStrategy strategy,
InvitationManager invMgr, InvitationManager invMgr,
ClientDnsOverwrite dns, ClientDnsOverwrite dns,
CloseableHttpClient client CloseableHttpClient client
) { ) {
this.cfg = cfg; this.cfg = cfg.getAuth();
this.mxCfg = mxCfg; this.mxCfg = cfg.getMatrix();
this.providers = new ArrayList<>(providers); this.providers = new ArrayList<>(providers);
this.strategy = strategy; this.strategy = strategy;
this.invMgr = invMgr; this.invMgr = invMgr;

View File

@@ -18,25 +18,25 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package io.kamax.mxisd.config; package io.kamax.mxisd.auth;
import org.springframework.context.annotation.Bean; import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
import org.springframework.context.annotation.Configuration;
import org.thymeleaf.resourceresolver.FileResourceResolver;
import org.thymeleaf.templateresolver.TemplateResolver;
@Configuration import java.util.ArrayList;
public class ThymeleafConfig { import java.util.List;
import java.util.function.Supplier;
import java.util.stream.Collectors;
@Bean public class AuthProviders {
public TemplateResolver getFileSystemResolver() {
TemplateResolver resolver = new TemplateResolver(); private static final List<Supplier<? extends AuthenticatorProvider>> suppliers = new ArrayList<>();
resolver.setPrefix("");
resolver.setSuffix(""); public static void register(Supplier<? extends AuthenticatorProvider> supplier) {
resolver.setCacheable(false); suppliers.add(supplier);
resolver.setOrder(1); }
resolver.setResourceResolver(new FileResourceResolver());
return resolver; public static List<? extends AuthenticatorProvider> get() {
return suppliers.stream().map(Supplier::get).collect(Collectors.toList());
} }
} }

View File

@@ -0,0 +1,29 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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;
import io.kamax.mxisd.Mxisd;
import java.util.function.Consumer;
public interface IdentityStoreSupplier extends Consumer<Mxisd> {
}

View File

@@ -33,20 +33,16 @@ import io.kamax.mxisd.exception.InternalServerError;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@Component
public class ExecAuthStore extends ExecStore implements AuthenticatorProvider { public class ExecAuthStore extends ExecStore implements AuthenticatorProvider {
private final Logger log = LoggerFactory.getLogger(ExecAuthStore.class); private transient final Logger log = LoggerFactory.getLogger(ExecAuthStore.class);
private ExecConfig.Auth cfg; private ExecConfig.Auth cfg;
@Autowired
public ExecAuthStore(ExecConfig cfg) { public ExecAuthStore(ExecConfig cfg) {
this.cfg = Objects.requireNonNull(cfg.getAuth()); this.cfg = Objects.requireNonNull(cfg.getAuth());
} }

View File

@@ -24,22 +24,19 @@ import io.kamax.matrix.MatrixID;
import io.kamax.matrix.json.GsonUtil; import io.kamax.matrix.json.GsonUtil;
import io.kamax.mxisd.config.ExecConfig; import io.kamax.mxisd.config.ExecConfig;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchRequest; import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.IDirectoryProvider; import io.kamax.mxisd.directory.IDirectoryProvider;
import io.kamax.mxisd.http.io.UserDirectorySearchRequest;
import io.kamax.mxisd.http.io.UserDirectorySearchResult;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class ExecDirectoryStore extends ExecStore implements IDirectoryProvider { public class ExecDirectoryStore extends ExecStore implements IDirectoryProvider {
private ExecConfig.Directory cfg; private ExecConfig.Directory cfg;
private MatrixConfig mxCfg; private MatrixConfig mxCfg;
@Autowired public ExecDirectoryStore(MxisdConfig cfg) {
public ExecDirectoryStore(ExecConfig cfg, MatrixConfig mxCfg) { this(cfg.getExec().getDirectory(), cfg.getMatrix());
this(cfg.getDirectory(), mxCfg);
} }
public ExecDirectoryStore(ExecConfig.Directory cfg, MatrixConfig mxCfg) { public ExecDirectoryStore(ExecConfig.Directory cfg, MatrixConfig mxCfg) {

View File

@@ -40,8 +40,6 @@ import io.kamax.mxisd.lookup.provider.IThreePidProvider;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
@@ -49,15 +47,13 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Component
public class ExecIdentityStore extends ExecStore implements IThreePidProvider { public class ExecIdentityStore extends ExecStore implements IThreePidProvider {
private final Logger log = LoggerFactory.getLogger(ExecIdentityStore.class); private transient final Logger log = LoggerFactory.getLogger(ExecIdentityStore.class);
private final ExecConfig.Identity cfg; private final ExecConfig.Identity cfg;
private final MatrixConfig mxCfg; private final MatrixConfig mxCfg;
@Autowired
public ExecIdentityStore(ExecConfig cfg, MatrixConfig mxCfg) { public ExecIdentityStore(ExecConfig cfg, MatrixConfig mxCfg) {
this(cfg.getIdentity(), mxCfg); this(cfg.getIdentity(), mxCfg);
} }

View File

@@ -0,0 +1,56 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.exec;
import io.kamax.mxisd.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
public class ExecIdentityStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
accept(mxisd.getConfig());
}
public void accept(MxisdConfig cfg) {
if (cfg.getExec().getAuth().isEnabled()) {
AuthProviders.register(() -> new ExecAuthStore(cfg.getExec()));
}
if (cfg.getExec().getDirectory().isEnabled()) {
DirectoryProviders.register(() -> new ExecDirectoryStore(cfg));
}
if (cfg.getExec().getIdentity().isEnabled()) {
ThreePidProviders.register(() -> new ExecIdentityStore(cfg.getExec(), cfg.getMatrix()));
}
if (cfg.getExec().getProfile().isEnabled()) {
ProfileProviders.register(() -> new ExecProfileStore(cfg.getExec()));
}
}
}

View File

@@ -28,19 +28,15 @@ import io.kamax.mxisd.profile.JsonProfileRequest;
import io.kamax.mxisd.profile.JsonProfileResult; import io.kamax.mxisd.profile.JsonProfileResult;
import io.kamax.mxisd.profile.ProfileProvider; import io.kamax.mxisd.profile.ProfileProvider;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Component
public class ExecProfileStore extends ExecStore implements ProfileProvider { public class ExecProfileStore extends ExecStore implements ProfileProvider {
private ExecConfig.Profile cfg; private ExecConfig.Profile cfg;
@Autowired
public ExecProfileStore(ExecConfig cfg) { public ExecProfileStore(ExecConfig cfg) {
this(cfg.getProfile()); this(cfg.getProfile());
} }

View File

@@ -47,7 +47,7 @@ public class ExecStore {
return GsonUtil.get().toJson(o); return GsonUtil.get().toJson(o);
} }
private final Logger log = LoggerFactory.getLogger(ExecStore.class); private transient final Logger log = LoggerFactory.getLogger(ExecStore.class);
private Supplier<ProcessExecutor> executorSupplier = () -> new ProcessExecutor().readOutput(true); private Supplier<ProcessExecutor> executorSupplier = () -> new ProcessExecutor().readOutput(true);

View File

@@ -29,6 +29,7 @@ import io.kamax.matrix._MatrixID;
import io.kamax.mxisd.UserIdType; import io.kamax.mxisd.UserIdType;
import io.kamax.mxisd.auth.provider.AuthenticatorProvider; import io.kamax.mxisd.auth.provider.AuthenticatorProvider;
import io.kamax.mxisd.auth.provider.BackendAuthResult; import io.kamax.mxisd.auth.provider.BackendAuthResult;
import io.kamax.mxisd.config.FirebaseConfig;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -38,10 +39,14 @@ import java.util.concurrent.TimeUnit;
public class GoogleFirebaseAuthenticator extends GoogleFirebaseBackend implements AuthenticatorProvider { public class GoogleFirebaseAuthenticator extends GoogleFirebaseBackend implements AuthenticatorProvider {
private Logger log = LoggerFactory.getLogger(GoogleFirebaseAuthenticator.class); private transient final Logger log = LoggerFactory.getLogger(GoogleFirebaseAuthenticator.class);
private PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); private PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
public GoogleFirebaseAuthenticator(FirebaseConfig cfg) {
this(cfg.isEnabled(), cfg.getCredentials(), cfg.getDatabase());
}
public GoogleFirebaseAuthenticator(boolean isEnabled, String credsPath, String db) { public GoogleFirebaseAuthenticator(boolean isEnabled, String credsPath, String db) {
super(isEnabled, "AuthenticationProvider", credsPath, db); super(isEnabled, "AuthenticationProvider", credsPath, db);
} }

View File

@@ -35,7 +35,7 @@ import java.io.IOException;
public class GoogleFirebaseBackend { public class GoogleFirebaseBackend {
private Logger log = LoggerFactory.getLogger(GoogleFirebaseBackend.class); private transient final Logger log = LoggerFactory.getLogger(GoogleFirebaseBackend.class);
private boolean isEnabled; private boolean isEnabled;
private FirebaseAuth fbAuth; private FirebaseAuth fbAuth;

View File

@@ -25,6 +25,7 @@ import com.google.firebase.tasks.OnFailureListener;
import com.google.firebase.tasks.OnSuccessListener; import com.google.firebase.tasks.OnSuccessListener;
import io.kamax.matrix.MatrixID; import io.kamax.matrix.MatrixID;
import io.kamax.matrix.ThreePidMedium; import io.kamax.matrix.ThreePidMedium;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.lookup.SingleLookupReply; import io.kamax.mxisd.lookup.SingleLookupReply;
import io.kamax.mxisd.lookup.SingleLookupRequest; import io.kamax.mxisd.lookup.SingleLookupRequest;
import io.kamax.mxisd.lookup.ThreePidMapping; import io.kamax.mxisd.lookup.ThreePidMapping;
@@ -40,9 +41,13 @@ import java.util.concurrent.TimeUnit;
public class GoogleFirebaseProvider extends GoogleFirebaseBackend implements IThreePidProvider { public class GoogleFirebaseProvider extends GoogleFirebaseBackend implements IThreePidProvider {
private Logger log = LoggerFactory.getLogger(GoogleFirebaseProvider.class); private transient final Logger log = LoggerFactory.getLogger(GoogleFirebaseProvider.class);
private String domain; private String domain;
public GoogleFirebaseProvider(MxisdConfig cfg) {
this(cfg.getFirebase().isEnabled(), cfg.getFirebase().getCredentials(), cfg.getFirebase().getDatabase(), cfg.getMatrix().getDomain());
}
public GoogleFirebaseProvider(boolean isEnabled, String credsPath, String db, String domain) { public GoogleFirebaseProvider(boolean isEnabled, String credsPath, String db, String domain) {
super(isEnabled, "ThreePidProvider", credsPath, db); super(isEnabled, "ThreePidProvider", credsPath, db);
this.domain = domain; this.domain = domain;

View File

@@ -1,6 +1,6 @@
/* /*
* mxisd - Matrix Identity Server Daemon * mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl * Copyright (C) 2018 Kamax Sarl
* *
* https://www.kamax.io/ * https://www.kamax.io/
* *
@@ -18,21 +18,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
package io.kamax.mxisd.spring; package io.kamax.mxisd.backend.firebase;
import io.kamax.mxisd.exception.ConfigurationException; import io.kamax.mxisd.Mxisd;
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer; import io.kamax.mxisd.auth.AuthProviders;
import org.springframework.boot.diagnostics.FailureAnalysis; import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.lookup.ThreePidProviders;
public class ConfigurationFailureAnalyzer extends AbstractFailureAnalyzer<ConfigurationException> { public class GoogleFirebaseStoreSupplier implements IdentityStoreSupplier {
@Override @Override
protected FailureAnalysis analyze(Throwable rootFailure, ConfigurationException cause) { public void accept(Mxisd mxisd) {
String message = cause.getMessage(); accept(mxisd.getConfig());
if (cause.getDetailedMessage().isPresent()) { }
message += " - " + cause.getDetailedMessage().get();
public void accept(MxisdConfig cfg) {
if (cfg.getFirebase().isEnabled()) {
AuthProviders.register(() -> new GoogleFirebaseAuthenticator(cfg.getFirebase()));
ThreePidProviders.register(() -> new GoogleFirebaseProvider(cfg));
} }
return new FailureAnalysis(message, "Double check the key value", cause);
} }
} }

View File

@@ -43,8 +43,6 @@ import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.util.HashSet; import java.util.HashSet;
@@ -52,14 +50,12 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
@Component
public class LdapAuthProvider extends LdapBackend implements AuthenticatorProvider { public class LdapAuthProvider extends LdapBackend implements AuthenticatorProvider {
private Logger log = LoggerFactory.getLogger(LdapAuthProvider.class); private transient final Logger log = LoggerFactory.getLogger(LdapAuthProvider.class);
private PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance(); private PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
@Autowired
public LdapAuthProvider(LdapConfig cfg, MatrixConfig mxCfg) { public LdapAuthProvider(LdapConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
} }

View File

@@ -45,7 +45,7 @@ public abstract class LdapBackend {
public static final String UID = "uid"; public static final String UID = "uid";
public static final String MATRIX_ID = "mxid"; public static final String MATRIX_ID = "mxid";
private Logger log = LoggerFactory.getLogger(LdapBackend.class); private transient final Logger log = LoggerFactory.getLogger(LdapBackend.class);
private LdapConfig cfg; private LdapConfig cfg;
private MatrixConfig mxCfg; private MatrixConfig mxCfg;

View File

@@ -22,9 +22,9 @@ package io.kamax.mxisd.backend.ldap;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.ldap.LdapConfig; import io.kamax.mxisd.config.ldap.LdapConfig;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.IDirectoryProvider; import io.kamax.mxisd.directory.IDirectoryProvider;
import io.kamax.mxisd.exception.InternalServerError; import io.kamax.mxisd.exception.InternalServerError;
import io.kamax.mxisd.http.io.UserDirectorySearchResult;
import io.kamax.mxisd.util.GsonUtil; import io.kamax.mxisd.util.GsonUtil;
import org.apache.directory.api.ldap.model.cursor.CursorException; 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.CursorLdapReferralException;
@@ -35,19 +35,15 @@ import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Component
public class LdapDirectoryProvider extends LdapBackend implements IDirectoryProvider { public class LdapDirectoryProvider extends LdapBackend implements IDirectoryProvider {
private Logger log = LoggerFactory.getLogger(LdapDirectoryProvider.class); private transient final Logger log = LoggerFactory.getLogger(LdapDirectoryProvider.class);
@Autowired
public LdapDirectoryProvider(LdapConfig cfg, MatrixConfig mxCfg) { public LdapDirectoryProvider(LdapConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
} }
@@ -95,7 +91,6 @@ public class LdapDirectoryProvider extends LdapBackend implements IDirectoryProv
} }
} }
} }
} catch (CursorLdapReferralException e) { } catch (CursorLdapReferralException e) {
log.warn("An entry is only available via referral, skipping"); log.warn("An entry is only available via referral, skipping");
} catch (IOException | LdapException | CursorException e) { } catch (IOException | LdapException | CursorException e) {

View File

@@ -36,8 +36,6 @@ import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -45,12 +43,10 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Component
public class LdapProfileProvider extends LdapBackend implements ProfileProvider { public class LdapProfileProvider extends LdapBackend implements ProfileProvider {
private transient Logger log = LoggerFactory.getLogger(LdapProfileProvider.class); private transient final Logger log = LoggerFactory.getLogger(LdapProfileProvider.class);
@Autowired
public LdapProfileProvider(LdapConfig cfg, MatrixConfig mxCfg) { public LdapProfileProvider(LdapConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
} }

View File

@@ -0,0 +1,47 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
public class LdapStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
accept(mxisd.getConfig());
}
public void accept(MxisdConfig cfg) {
if (cfg.getLdap().isEnabled()) {
AuthProviders.register(() -> new LdapAuthProvider(cfg.getLdap(), cfg.getMatrix()));
DirectoryProviders.register(() -> new LdapDirectoryProvider(cfg.getLdap(), cfg.getMatrix()));
ThreePidProviders.register(() -> new LdapThreePidProvider(cfg.getLdap(), cfg.getMatrix()));
ProfileProviders.register(() -> new LdapProfileProvider(cfg.getLdap(), cfg.getMatrix()));
}
}
}

View File

@@ -37,17 +37,15 @@ import org.apache.directory.api.ldap.model.message.SearchScope;
import org.apache.directory.ldap.client.api.LdapConnection; import org.apache.directory.ldap.client.api.LdapConnection;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Component
public class LdapThreePidProvider extends LdapBackend implements IThreePidProvider { public class LdapThreePidProvider extends LdapBackend implements IThreePidProvider {
private Logger log = LoggerFactory.getLogger(LdapThreePidProvider.class); private transient final Logger log = LoggerFactory.getLogger(LdapThreePidProvider.class);
public LdapThreePidProvider(LdapConfig cfg, MatrixConfig mxCfg) { public LdapThreePidProvider(LdapConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);

View File

@@ -23,9 +23,7 @@ package io.kamax.mxisd.backend.ldap.netiq;
import io.kamax.mxisd.backend.ldap.LdapAuthProvider; import io.kamax.mxisd.backend.ldap.LdapAuthProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig; import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig;
import org.springframework.stereotype.Component;
@Component
public class NetIqLdapAuthProvider extends LdapAuthProvider { public class NetIqLdapAuthProvider extends LdapAuthProvider {
public NetIqLdapAuthProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) { public NetIqLdapAuthProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) {

View File

@@ -23,9 +23,7 @@ package io.kamax.mxisd.backend.ldap.netiq;
import io.kamax.mxisd.backend.ldap.LdapDirectoryProvider; import io.kamax.mxisd.backend.ldap.LdapDirectoryProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig; import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig;
import org.springframework.stereotype.Component;
@Component
public class NetIqLdapDirectoryProvider extends LdapDirectoryProvider { public class NetIqLdapDirectoryProvider extends LdapDirectoryProvider {
public NetIqLdapDirectoryProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) { public NetIqLdapDirectoryProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) {

View File

@@ -24,13 +24,9 @@ import io.kamax.matrix._MatrixID;
import io.kamax.mxisd.backend.ldap.LdapProfileProvider; import io.kamax.mxisd.backend.ldap.LdapProfileProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig; import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class NetIqLdapProfileProvider extends LdapProfileProvider { public class NetIqLdapProfileProvider extends LdapProfileProvider {
@Autowired
public NetIqLdapProfileProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) { public NetIqLdapProfileProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
} }

View File

@@ -0,0 +1,47 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.netiq;
import io.kamax.mxisd.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
public class NetIqLdapStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
accept(mxisd.getConfig());
}
public void accept(MxisdConfig cfg) {
if (cfg.getLdap().isEnabled()) {
AuthProviders.register(() -> new NetIqLdapAuthProvider(cfg.getNetiq(), cfg.getMatrix()));
DirectoryProviders.register(() -> new NetIqLdapDirectoryProvider(cfg.getNetiq(), cfg.getMatrix()));
ThreePidProviders.register(() -> new NetIqLdapThreePidProvider(cfg.getNetiq(), cfg.getMatrix()));
ProfileProviders.register(() -> new NetIqLdapProfileProvider(cfg.getNetiq(), cfg.getMatrix()));
}
}
}

View File

@@ -23,9 +23,7 @@ package io.kamax.mxisd.backend.ldap.netiq;
import io.kamax.mxisd.backend.ldap.LdapThreePidProvider; import io.kamax.mxisd.backend.ldap.LdapThreePidProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig; import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig;
import org.springframework.stereotype.Component;
@Component
public class NetIqLdapThreePidProvider extends LdapThreePidProvider { public class NetIqLdapThreePidProvider extends LdapThreePidProvider {
public NetIqLdapThreePidProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) { public NetIqLdapThreePidProvider(NetIqLdapConfig cfg, MatrixConfig mxCfg) {

View File

@@ -31,8 +31,8 @@ import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.memory.MemoryIdentityConfig; import io.kamax.mxisd.config.memory.MemoryIdentityConfig;
import io.kamax.mxisd.config.memory.MemoryStoreConfig; import io.kamax.mxisd.config.memory.MemoryStoreConfig;
import io.kamax.mxisd.config.memory.MemoryThreePid; import io.kamax.mxisd.config.memory.MemoryThreePid;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.IDirectoryProvider; import io.kamax.mxisd.directory.IDirectoryProvider;
import io.kamax.mxisd.http.io.UserDirectorySearchResult;
import io.kamax.mxisd.lookup.SingleLookupReply; import io.kamax.mxisd.lookup.SingleLookupReply;
import io.kamax.mxisd.lookup.SingleLookupRequest; import io.kamax.mxisd.lookup.SingleLookupRequest;
import io.kamax.mxisd.lookup.ThreePidMapping; import io.kamax.mxisd.lookup.ThreePidMapping;
@@ -41,8 +41,6 @@ import io.kamax.mxisd.profile.ProfileProvider;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
@@ -51,15 +49,13 @@ import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
@Component
public class MemoryIdentityStore implements AuthenticatorProvider, IDirectoryProvider, IThreePidProvider, ProfileProvider { public class MemoryIdentityStore implements AuthenticatorProvider, IDirectoryProvider, IThreePidProvider, ProfileProvider {
private final Logger logger = LoggerFactory.getLogger(MemoryIdentityStore.class); private transient final Logger logger = LoggerFactory.getLogger(MemoryIdentityStore.class);
private final MatrixConfig mxCfg; private final MatrixConfig mxCfg;
private final MemoryStoreConfig cfg; private final MemoryStoreConfig cfg;
@Autowired
public MemoryIdentityStore(MatrixConfig mxCfg, MemoryStoreConfig cfg) { public MemoryIdentityStore(MatrixConfig mxCfg, MemoryStoreConfig cfg) {
this.mxCfg = mxCfg; this.mxCfg = mxCfg;
this.cfg = cfg; this.cfg = cfg;

View File

@@ -0,0 +1,51 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.memory;
import io.kamax.mxisd.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
import java.util.function.Supplier;
public class MemoryIdentityStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
accept(mxisd.getConfig());
}
public void accept(MxisdConfig cfg) {
if (cfg.getMemory().isEnabled()) {
Supplier<MemoryIdentityStore> supplier = () -> new MemoryIdentityStore(cfg.getMatrix(), cfg.getMemory());
AuthProviders.register(supplier);
DirectoryProviders.register(supplier);
ThreePidProviders.register(supplier);
ProfileProviders.register(supplier);
}
}
}

View File

@@ -27,15 +27,11 @@ import io.kamax.mxisd.config.rest.RestBackendConfig;
import io.kamax.mxisd.util.RestClientUtils; import io.kamax.mxisd.util.RestClientUtils;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
@Component
public class RestAuthProvider extends RestProvider implements AuthenticatorProvider { public class RestAuthProvider extends RestProvider implements AuthenticatorProvider {
@Autowired
public RestAuthProvider(RestBackendConfig cfg) { public RestAuthProvider(RestBackendConfig cfg) {
super(cfg); super(cfg);
} }

View File

@@ -23,20 +23,18 @@ package io.kamax.mxisd.backend.rest;
import io.kamax.matrix.MatrixID; import io.kamax.matrix.MatrixID;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.rest.RestBackendConfig; import io.kamax.mxisd.config.rest.RestBackendConfig;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchRequest;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.IDirectoryProvider; import io.kamax.mxisd.directory.IDirectoryProvider;
import io.kamax.mxisd.exception.InternalServerError; import io.kamax.mxisd.exception.InternalServerError;
import io.kamax.mxisd.http.io.UserDirectorySearchRequest;
import io.kamax.mxisd.http.io.UserDirectorySearchResult;
import io.kamax.mxisd.util.RestClientUtils; import io.kamax.mxisd.util.RestClientUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.CloseableHttpResponse;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
@Component
public class RestDirectoryProvider extends RestProvider implements IDirectoryProvider { public class RestDirectoryProvider extends RestProvider implements IDirectoryProvider {
private MatrixConfig mxCfg; private MatrixConfig mxCfg;

View File

@@ -40,7 +40,6 @@ import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity; import org.apache.http.entity.StringEntity;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.net.URISyntaxException; import java.net.URISyntaxException;
@@ -48,10 +47,9 @@ import java.nio.charset.StandardCharsets;
import java.util.*; import java.util.*;
import java.util.function.Function; import java.util.function.Function;
@Component
public class RestProfileProvider extends RestProvider implements ProfileProvider { public class RestProfileProvider extends RestProvider implements ProfileProvider {
private final Logger log = LoggerFactory.getLogger(RestProfileProvider.class); private transient final Logger log = LoggerFactory.getLogger(RestProfileProvider.class);
public RestProfileProvider(RestBackendConfig cfg) { public RestProfileProvider(RestBackendConfig cfg) {
super(cfg); super(cfg);

View File

@@ -0,0 +1,47 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
public class RestStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
accept(mxisd.getConfig());
}
public void accept(MxisdConfig cfg) {
if (cfg.getRest().isEnabled()) {
AuthProviders.register(() -> new RestAuthProvider(cfg.getRest()));
DirectoryProviders.register(() -> new RestDirectoryProvider(cfg.getRest(), cfg.getMatrix()));
ThreePidProviders.register(() -> new RestThreePidProvider(cfg.getRest(), cfg.getMatrix()));
ProfileProviders.register(() -> new RestProfileProvider(cfg.getRest()));
}
}
}

View File

@@ -35,8 +35,6 @@ import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
@@ -44,14 +42,12 @@ import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
@Component
public class RestThreePidProvider extends RestProvider implements IThreePidProvider { public class RestThreePidProvider extends RestProvider implements IThreePidProvider {
private Logger log = LoggerFactory.getLogger(RestThreePidProvider.class); private transient final Logger log = LoggerFactory.getLogger(RestThreePidProvider.class);
private MatrixConfig mxCfg; // FIXME should be done in the lookup manager private MatrixConfig mxCfg; // FIXME should be done in the lookup manager
@Autowired
public RestThreePidProvider(RestBackendConfig cfg, MatrixConfig mxCfg) { public RestThreePidProvider(RestBackendConfig cfg, MatrixConfig mxCfg) {
super(cfg); super(cfg);
this.mxCfg = mxCfg; this.mxCfg = mxCfg;

View File

@@ -39,7 +39,7 @@ import java.util.Optional;
public abstract class SqlProfileProvider implements ProfileProvider { public abstract class SqlProfileProvider implements ProfileProvider {
private Logger log = LoggerFactory.getLogger(SqlProfileProvider.class); private transient final Logger log = LoggerFactory.getLogger(SqlProfileProvider.class);
private SqlConfig.Profile cfg; private SqlConfig.Profile cfg;

View File

@@ -41,7 +41,7 @@ import java.util.Optional;
public abstract class SqlThreePidProvider implements IThreePidProvider { public abstract class SqlThreePidProvider implements IThreePidProvider {
private Logger log = LoggerFactory.getLogger(SqlThreePidProvider.class); private transient final Logger log = LoggerFactory.getLogger(SqlThreePidProvider.class);
private SqlConfig cfg; private SqlConfig cfg;
private MatrixConfig mxCfg; private MatrixConfig mxCfg;

View File

@@ -27,20 +27,19 @@ import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig;
import io.kamax.mxisd.invitation.InvitationManager; import io.kamax.mxisd.invitation.InvitationManager;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class GenericSqlAuthProvider implements AuthenticatorProvider { public class GenericSqlAuthProvider implements AuthenticatorProvider {
private Logger log = LoggerFactory.getLogger(GenericSqlAuthProvider.class); private transient final Logger log = LoggerFactory.getLogger(GenericSqlAuthProvider.class);
@Autowired
private GenericSqlProviderConfig cfg; private GenericSqlProviderConfig cfg;
@Autowired
private InvitationManager invMgr; private InvitationManager invMgr;
public GenericSqlAuthProvider(GenericSqlProviderConfig cfg, InvitationManager invMgr) {
this.cfg = cfg;
this.invMgr = invMgr;
}
@Override @Override
public boolean isEnabled() { public boolean isEnabled() {
return cfg.getAuth().isEnabled(); return cfg.getAuth().isEnabled();

View File

@@ -25,9 +25,9 @@ import io.kamax.mxisd.backend.sql.SqlConnectionPool;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.sql.SqlConfig; import io.kamax.mxisd.config.sql.SqlConfig;
import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig; import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.IDirectoryProvider; import io.kamax.mxisd.directory.IDirectoryProvider;
import io.kamax.mxisd.exception.InternalServerError; import io.kamax.mxisd.exception.InternalServerError;
import io.kamax.mxisd.http.io.UserDirectorySearchResult;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@@ -38,11 +38,11 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional; import java.util.Optional;
import static io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult.Result; import static io.kamax.mxisd.http.io.UserDirectorySearchResult.Result;
public abstract class GenericSqlDirectoryProvider implements IDirectoryProvider { public class GenericSqlDirectoryProvider implements IDirectoryProvider {
private Logger log = LoggerFactory.getLogger(GenericSqlDirectoryProvider.class); private transient final Logger log = LoggerFactory.getLogger(GenericSqlDirectoryProvider.class);
protected SqlConfig cfg; protected SqlConfig cfg;
protected MatrixConfig mxCfg; protected MatrixConfig mxCfg;

View File

@@ -22,9 +22,7 @@ package io.kamax.mxisd.backend.sql.generic;
import io.kamax.mxisd.backend.sql.SqlProfileProvider; import io.kamax.mxisd.backend.sql.SqlProfileProvider;
import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig; import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig;
import org.springframework.stereotype.Component;
@Component
public class GenericSqlProfileProvider extends SqlProfileProvider { public class GenericSqlProfileProvider extends SqlProfileProvider {
public GenericSqlProfileProvider(GenericSqlProviderConfig cfg) { public GenericSqlProfileProvider(GenericSqlProviderConfig cfg) {

View File

@@ -0,0 +1,51 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.generic;
import io.kamax.mxisd.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
public class GenericSqlStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
if (mxisd.getConfig().getSql().getAuth().isEnabled()) {
AuthProviders.register(() -> new GenericSqlAuthProvider(mxisd.getConfig().getSql(), mxisd.getInvitationManager()));
}
if (mxisd.getConfig().getSql().getDirectory().isEnabled()) {
DirectoryProviders.register(() -> new GenericSqlDirectoryProvider(mxisd.getConfig().getSql(), mxisd.getConfig().getMatrix()));
}
if (mxisd.getConfig().getSql().getIdentity().isEnabled()) {
ThreePidProviders.register(() -> new GenericSqlThreePidProvider(mxisd.getConfig().getSql(), mxisd.getConfig().getMatrix()));
}
if (mxisd.getConfig().getSql().getProfile().isEnabled()) {
ProfileProviders.register(() -> new GenericSqlProfileProvider(mxisd.getConfig().getSql()));
}
}
}

View File

@@ -23,13 +23,9 @@ package io.kamax.mxisd.backend.sql.generic;
import io.kamax.mxisd.backend.sql.SqlThreePidProvider; import io.kamax.mxisd.backend.sql.SqlThreePidProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig; import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class GenericSqlThreePidProvider extends SqlThreePidProvider { public class GenericSqlThreePidProvider extends SqlThreePidProvider {
@Autowired
public GenericSqlThreePidProvider(GenericSqlProviderConfig cfg, MatrixConfig mxCfg) { public GenericSqlThreePidProvider(GenericSqlProviderConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
} }

View File

@@ -22,19 +22,15 @@ package io.kamax.mxisd.backend.sql.synapse;
import io.kamax.mxisd.backend.sql.SqlConnectionPool; import io.kamax.mxisd.backend.sql.SqlConnectionPool;
import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig; import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.util.Optional; import java.util.Optional;
@Component
public class Synapse { public class Synapse {
private SqlConnectionPool pool; private SqlConnectionPool pool;
@Autowired
public Synapse(SynapseSqlProviderConfig sqlCfg) { public Synapse(SynapseSqlProviderConfig sqlCfg) {
this.pool = new SqlConnectionPool(sqlCfg); this.pool = new SqlConnectionPool(sqlCfg);
} }

View File

@@ -24,32 +24,15 @@ import io.kamax.mxisd.backend.sql.generic.GenericSqlDirectoryProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig; import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig;
import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig; import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Objects; import java.util.Objects;
@Component
public class SynapseSqlDirectoryProvider extends GenericSqlDirectoryProvider { public class SynapseSqlDirectoryProvider extends GenericSqlDirectoryProvider {
@Autowired
public SynapseSqlDirectoryProvider(SynapseSqlProviderConfig cfg, MatrixConfig mxCfg) { public SynapseSqlDirectoryProvider(SynapseSqlProviderConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
}
@Override
protected void setParameters(PreparedStatement stmt, String searchTerm) throws SQLException {
stmt.setString(1, "%" + searchTerm + "%");
}
@PostConstruct
public void build() {
if (!isEnabled()) {
return;
}
GenericSqlProviderConfig.Type queries = cfg.getDirectory().getQuery(); GenericSqlProviderConfig.Type queries = cfg.getDirectory().getQuery();
if (Objects.isNull(queries.getName().getValue())) { if (Objects.isNull(queries.getName().getValue())) {
@@ -60,4 +43,9 @@ public class SynapseSqlDirectoryProvider extends GenericSqlDirectoryProvider {
} }
} }
@Override
protected void setParameters(PreparedStatement stmt, String searchTerm) throws SQLException {
stmt.setString(1, "%" + searchTerm + "%");
}
} }

View File

@@ -22,13 +22,9 @@ package io.kamax.mxisd.backend.sql.synapse;
import io.kamax.mxisd.backend.sql.SqlProfileProvider; import io.kamax.mxisd.backend.sql.SqlProfileProvider;
import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig; import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SynapseSqlProfileProvider extends SqlProfileProvider { public class SynapseSqlProfileProvider extends SqlProfileProvider {
@Autowired
public SynapseSqlProfileProvider(SynapseSqlProviderConfig cfg) { public SynapseSqlProfileProvider(SynapseSqlProviderConfig cfg) {
super(cfg); super(cfg);
} }

View File

@@ -0,0 +1,51 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.synapse;
import io.kamax.mxisd.Mxisd;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MxisdConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
import io.kamax.mxisd.profile.ProfileProviders;
public class SynapseSqlStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd mxisd) {
accept(mxisd.getConfig());
}
public void accept(MxisdConfig cfg) {
if (cfg.getSynapseSql().getDirectory().isEnabled()) {
DirectoryProviders.register(() -> new SynapseSqlDirectoryProvider(cfg.getSynapseSql(), cfg.getMatrix()));
}
if (cfg.getSynapseSql().getIdentity().isEnabled()) {
ThreePidProviders.register(() -> new SynapseSqlThreePidProvider(cfg.getSynapseSql(), cfg.getMatrix()));
}
if (cfg.getSynapseSql().getProfile().isEnabled()) {
ProfileProviders.register(() -> new SynapseSqlProfileProvider(cfg.getSynapseSql()));
}
}
}

View File

@@ -23,13 +23,9 @@ package io.kamax.mxisd.backend.sql.synapse;
import io.kamax.mxisd.backend.sql.SqlThreePidProvider; import io.kamax.mxisd.backend.sql.SqlThreePidProvider;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig; import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class SynapseSqlThreePidProvider extends SqlThreePidProvider { public class SynapseSqlThreePidProvider extends SqlThreePidProvider {
@Autowired
public SynapseSqlThreePidProvider(SynapseSqlProviderConfig cfg, MatrixConfig mxCfg) { public SynapseSqlThreePidProvider(SynapseSqlProviderConfig cfg, MatrixConfig mxCfg) {
super(cfg, mxCfg); super(cfg, mxCfg);
} }

View File

@@ -28,17 +28,13 @@ import io.kamax.mxisd.auth.provider.BackendAuthResult;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class WordpressAuthProvider implements AuthenticatorProvider { public class WordpressAuthProvider implements AuthenticatorProvider {
private final Logger log = LoggerFactory.getLogger(WordpressAuthProvider.class); private transient final Logger log = LoggerFactory.getLogger(WordpressAuthProvider.class);
private WordpressRestBackend wordpress; private WordpressRestBackend wordpress;
@Autowired
public WordpressAuthProvider(WordpressRestBackend wordpress) { public WordpressAuthProvider(WordpressRestBackend wordpress) {
this.wordpress = wordpress; this.wordpress = wordpress;
} }

View File

@@ -23,13 +23,11 @@ package io.kamax.mxisd.backend.wordpress;
import io.kamax.matrix.MatrixID; import io.kamax.matrix.MatrixID;
import io.kamax.mxisd.config.MatrixConfig; import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.wordpress.WordpressConfig; import io.kamax.mxisd.config.wordpress.WordpressConfig;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.IDirectoryProvider; import io.kamax.mxisd.directory.IDirectoryProvider;
import io.kamax.mxisd.exception.InternalServerError; import io.kamax.mxisd.exception.InternalServerError;
import io.kamax.mxisd.http.io.UserDirectorySearchResult;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@@ -37,16 +35,14 @@ import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.util.Optional; import java.util.Optional;
@Component
public class WordpressDirectoryProvider implements IDirectoryProvider { public class WordpressDirectoryProvider implements IDirectoryProvider {
private final Logger log = LoggerFactory.getLogger(WordpressDirectoryProvider.class); private transient final Logger log = LoggerFactory.getLogger(WordpressDirectoryProvider.class);
private WordpressConfig cfg; private WordpressConfig cfg;
private WordressSqlBackend wordpress; private WordressSqlBackend wordpress;
private MatrixConfig mxCfg; private MatrixConfig mxCfg;
@Autowired
public WordpressDirectoryProvider(WordpressConfig cfg, WordressSqlBackend wordpress, MatrixConfig mxCfg) { public WordpressDirectoryProvider(WordpressConfig cfg, WordressSqlBackend wordpress, MatrixConfig mxCfg) {
this.cfg = cfg; this.cfg = cfg;
this.wordpress = wordpress; this.wordpress = wordpress;

View File

@@ -34,15 +34,12 @@ import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException; import java.io.IOException;
@Component
public class WordpressRestBackend { public class WordpressRestBackend {
private final Logger log = LoggerFactory.getLogger(WordpressRestBackend.class); private transient final Logger log = LoggerFactory.getLogger(WordpressRestBackend.class);
private final String jsonPath = "/wp-json"; private final String jsonPath = "/wp-json";
private final String jwtPath = "/jwt-auth/v1"; private final String jwtPath = "/jwt-auth/v1";
@@ -54,7 +51,6 @@ public class WordpressRestBackend {
private String token; private String token;
@Autowired
public WordpressRestBackend(WordpressConfig cfg, CloseableHttpClient client) { public WordpressRestBackend(WordpressConfig cfg, CloseableHttpClient client) {
this.cfg = cfg; this.cfg = cfg;
this.client = client; this.client = client;

View File

@@ -0,0 +1,48 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.wordpress;
import io.kamax.mxisd.Mxisd;
import io.kamax.mxisd.auth.AuthProviders;
import io.kamax.mxisd.backend.IdentityStoreSupplier;
import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.config.wordpress.WordpressConfig;
import io.kamax.mxisd.directory.DirectoryProviders;
import io.kamax.mxisd.lookup.ThreePidProviders;
public class WordpressStoreSupplier implements IdentityStoreSupplier {
@Override
public void accept(Mxisd m) {
WordpressConfig wpCfg = m.getConfig().getWordpress();
MatrixConfig mxCfg = m.getConfig().getMatrix();
if (m.getConfig().getWordpress().isEnabled()) {
WordpressRestBackend restBackend = new WordpressRestBackend(wpCfg, m.getHttpClient());
WordressSqlBackend sqlBackend = new WordressSqlBackend(wpCfg);
AuthProviders.register(() -> new WordpressAuthProvider(restBackend));
DirectoryProviders.register(() -> new WordpressDirectoryProvider(wpCfg, sqlBackend, mxCfg));
ThreePidProviders.register(() -> new WordpressThreePidProvider(mxCfg, wpCfg, sqlBackend));
}
}
}

View File

@@ -31,8 +31,6 @@ import io.kamax.mxisd.lookup.ThreePidMapping;
import io.kamax.mxisd.lookup.provider.IThreePidProvider; import io.kamax.mxisd.lookup.provider.IThreePidProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection; import java.sql.Connection;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@@ -42,16 +40,14 @@ import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@Component
public class WordpressThreePidProvider implements IThreePidProvider { public class WordpressThreePidProvider implements IThreePidProvider {
private final Logger log = LoggerFactory.getLogger(WordpressThreePidProvider.class); private transient final Logger log = LoggerFactory.getLogger(WordpressThreePidProvider.class);
private MatrixConfig mxCfg; private MatrixConfig mxCfg;
private WordpressConfig cfg; private WordpressConfig cfg;
private WordressSqlBackend wordpress; private WordressSqlBackend wordpress;
@Autowired
public WordpressThreePidProvider(MatrixConfig mxCfg, WordpressConfig cfg, WordressSqlBackend wordpress) { public WordpressThreePidProvider(MatrixConfig mxCfg, WordpressConfig cfg, WordressSqlBackend wordpress) {
this.mxCfg = mxCfg; this.mxCfg = mxCfg;
this.cfg = cfg; this.cfg = cfg;

View File

@@ -24,22 +24,17 @@ import com.mchange.v2.c3p0.ComboPooledDataSource;
import io.kamax.mxisd.config.wordpress.WordpressConfig; import io.kamax.mxisd.config.wordpress.WordpressConfig;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection; import java.sql.Connection;
import java.sql.SQLException; import java.sql.SQLException;
@Component
public class WordressSqlBackend { public class WordressSqlBackend {
private Logger log = LoggerFactory.getLogger(WordressSqlBackend.class); private transient final Logger log = LoggerFactory.getLogger(WordressSqlBackend.class);
private WordpressConfig cfg; private WordpressConfig cfg;
private ComboPooledDataSource ds; private ComboPooledDataSource ds;
@Autowired
public WordressSqlBackend(WordpressConfig cfg) { public WordressSqlBackend(WordpressConfig cfg) {
this.cfg = cfg; this.cfg = cfg;

View File

@@ -20,16 +20,10 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@Configuration
@ConfigurationProperties(prefix = "auth")
public class AuthenticationConfig { public class AuthenticationConfig {
public static class Rule { public static class Rule {
@@ -102,7 +96,6 @@ public class AuthenticationConfig {
this.rewrite = rewrite; this.rewrite = rewrite;
} }
@PostConstruct
public void build() { public void build() {
getRewrite().getUser().getRules().forEach(mapping -> mapping.setPattern(Pattern.compile(mapping.getRegex()))); getRewrite().getUser().getRules().forEach(mapping -> mapping.setPattern(Pattern.compile(mapping.getRegex())));
} }

View File

@@ -20,14 +20,9 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.Objects; import java.util.Objects;
@Configuration
@ConfigurationProperties(prefix = "lookup.bulk")
public class BulkLookupConfig { public class BulkLookupConfig {
private Boolean enabled; private Boolean enabled;

View File

@@ -22,16 +22,12 @@ package io.kamax.mxisd.config;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("directory")
public class DirectoryConfig { public class DirectoryConfig {
private final transient Logger log = LoggerFactory.getLogger(DnsOverwriteConfig.class); private final static Logger log = LoggerFactory.getLogger(DirectoryConfig.class);
public static class Exclude { public static class Exclude {
@@ -68,7 +64,7 @@ public class DirectoryConfig {
} }
@PostConstruct @PostConstruct
public void buid() { public void build() {
log.info("--- Directory config ---"); log.info("--- Directory config ---");
log.info("Exclude:"); log.info("Exclude:");
log.info("\tHomeserver: {}", getExclude().getHomeserver()); log.info("\tHomeserver: {}", getExclude().getHomeserver());

View File

@@ -24,18 +24,14 @@ import com.google.gson.Gson;
import io.kamax.mxisd.util.GsonUtil; import io.kamax.mxisd.util.GsonUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Configuration
@ConfigurationProperties("dns.overwrite")
public class DnsOverwriteConfig { public class DnsOverwriteConfig {
private Logger log = LoggerFactory.getLogger(DnsOverwriteConfig.class); private transient final Logger log = LoggerFactory.getLogger(DnsOverwriteConfig.class);
public static class Entry { public static class Entry {

View File

@@ -21,14 +21,10 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.*; import java.util.*;
@Configuration
@ConfigurationProperties("exec")
public class ExecConfig { public class ExecConfig {
public class IO { public class IO {
@@ -517,7 +513,7 @@ public class ExecConfig {
} }
@PostConstruct @PostConstruct
public ExecConfig compute() { public ExecConfig build() {
if (Objects.isNull(getAuth().isEnabled())) { if (Objects.isNull(getAuth().isEnabled())) {
getAuth().setEnabled(isEnabled()); getAuth().setEnabled(isEnabled());
} }

View File

@@ -20,27 +20,14 @@
package io.kamax.mxisd.config; 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.Logger;
import org.slf4j.LoggerFactory; 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; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("firebase")
public class FirebaseConfig { public class FirebaseConfig {
private Logger log = LoggerFactory.getLogger(FirebaseConfig.class); private transient final Logger log = LoggerFactory.getLogger(FirebaseConfig.class);
@Autowired
private MatrixConfig mxCfg;
private boolean enabled; private boolean enabled;
private String credentials; private String credentials;
@@ -80,14 +67,4 @@ public class FirebaseConfig {
} }
} }
@Bean
public AuthenticatorProvider getAuthProvider() {
return new GoogleFirebaseAuthenticator(enabled, credentials, database);
}
@Bean
public IThreePidProvider getLookupProvider() {
return new GoogleFirebaseProvider(enabled, credentials, database, mxCfg.getDomain());
}
} }

View File

@@ -20,14 +20,9 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "forward")
public class ForwardConfig { public class ForwardConfig {
private List<String> servers = new ArrayList<>(); private List<String> servers = new ArrayList<>();
@@ -40,4 +35,8 @@ public class ForwardConfig {
this.servers = servers; this.servers = servers;
} }
public void build() {
// no-op
}
} }

View File

@@ -23,16 +23,12 @@ package io.kamax.mxisd.config;
import io.kamax.mxisd.util.GsonUtil; import io.kamax.mxisd.util.GsonUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("invite")
public class InvitationConfig { public class InvitationConfig {
private final Logger log = LoggerFactory.getLogger(InvitationConfig.class); private transient final Logger log = LoggerFactory.getLogger(InvitationConfig.class);
public static class Resolution { public static class Resolution {

View File

@@ -22,13 +22,9 @@ package io.kamax.mxisd.config;
import io.kamax.mxisd.exception.ConfigurationException; import io.kamax.mxisd.exception.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties(prefix = "key")
public class KeyConfig { public class KeyConfig {
private String path; private String path;

View File

@@ -21,15 +21,11 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@Configuration
@ConfigurationProperties("matrix.listener")
public class ListenerConfig { public class ListenerConfig {
public static class Token { public static class Token {

View File

@@ -25,16 +25,12 @@ import io.kamax.mxisd.exception.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@Configuration
@ConfigurationProperties("matrix")
public class MatrixConfig { public class MatrixConfig {
public static class Identity { public static class Identity {
@@ -57,10 +53,11 @@ public class MatrixConfig {
} }
} }
private Logger log = LoggerFactory.getLogger(MatrixConfig.class); private transient final Logger log = LoggerFactory.getLogger(MatrixConfig.class);
private String domain; private String domain;
private Identity identity = new Identity(); private Identity identity = new Identity();
private ListenerConfig listener = new ListenerConfig();
public String getDomain() { public String getDomain() {
return domain; return domain;
@@ -78,6 +75,14 @@ public class MatrixConfig {
this.identity = identity; this.identity = identity;
} }
public ListenerConfig getListener() {
return listener;
}
public void setListener(ListenerConfig listener) {
this.listener = listener;
}
@PostConstruct @PostConstruct
public void build() { public void build() {
log.info("--- Matrix config ---"); log.info("--- Matrix config ---");

View File

@@ -0,0 +1,329 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sàrl
*
* https://www.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.JsonObject;
import io.kamax.mxisd.config.ldap.generic.GenericLdapConfig;
import io.kamax.mxisd.config.ldap.netiq.NetIqLdapConfig;
import io.kamax.mxisd.config.memory.MemoryStoreConfig;
import io.kamax.mxisd.config.rest.RestBackendConfig;
import io.kamax.mxisd.config.sql.generic.GenericSqlProviderConfig;
import io.kamax.mxisd.config.sql.synapse.SynapseSqlProviderConfig;
import io.kamax.mxisd.config.threepid.notification.NotificationConfig;
import io.kamax.mxisd.config.wordpress.WordpressConfig;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashMap;
import java.util.Map;
public class MxisdConfig {
private static final Logger log = LoggerFactory.getLogger(MxisdConfig.class);
public static class Dns {
private DnsOverwriteConfig overwrite = new DnsOverwriteConfig();
public DnsOverwriteConfig getOverwrite() {
return overwrite;
}
public void setOverwrite(DnsOverwriteConfig overwrite) {
this.overwrite = overwrite;
}
}
public static class Lookup {
private BulkLookupConfig bulk = new BulkLookupConfig();
private RecursiveLookupConfig recursive = new RecursiveLookupConfig();
public BulkLookupConfig getBulk() {
return bulk;
}
public void setBulk(BulkLookupConfig bulk) {
this.bulk = bulk;
}
public RecursiveLookupConfig getRecursive() {
return recursive;
}
public void setRecursive(RecursiveLookupConfig recursive) {
this.recursive = recursive;
}
public void build() {
getBulk().build();
getRecursive().build();
}
}
public static class Threepid {
private Map<String, JsonObject> medium = new HashMap<>();
public Map<String, JsonObject> getMedium() {
return medium;
}
public void setMedium(Map<String, JsonObject> medium) {
this.medium = medium;
}
}
private AuthenticationConfig auth = new AuthenticationConfig();
private DirectoryConfig directory = new DirectoryConfig();
private Dns dns = new Dns();
private ExecConfig exec = new ExecConfig();
private FirebaseConfig firebase = new FirebaseConfig();
private ForwardConfig forward = new ForwardConfig();
private InvitationConfig invite = new InvitationConfig();
private KeyConfig key = new KeyConfig();
private GenericLdapConfig ldap = new GenericLdapConfig();
private Lookup lookup = new Lookup();
private MatrixConfig matrix = new MatrixConfig();
private MemoryStoreConfig memory = new MemoryStoreConfig();
private NotificationConfig notification = new NotificationConfig();
private NetIqLdapConfig netiq = new NetIqLdapConfig();
private ServerConfig server = new ServerConfig();
private SessionConfig session = new SessionConfig();
private StorageConfig storage = new StorageConfig();
private RestBackendConfig rest = new RestBackendConfig();
private GenericSqlProviderConfig sql = new GenericSqlProviderConfig();
private SynapseSqlProviderConfig synapseSql = new SynapseSqlProviderConfig();
private ViewConfig view = new ViewConfig();
private WordpressConfig wordpress = new WordpressConfig();
public AuthenticationConfig getAuth() {
return auth;
}
public void setAuth(AuthenticationConfig auth) {
this.auth = auth;
}
public DirectoryConfig getDirectory() {
return directory;
}
public void setDirectory(DirectoryConfig directory) {
this.directory = directory;
}
public Dns getDns() {
return dns;
}
public void setDns(Dns dns) {
this.dns = dns;
}
public ExecConfig getExec() {
return exec;
}
public void setExec(ExecConfig exec) {
this.exec = exec;
}
public FirebaseConfig getFirebase() {
return firebase;
}
public void setFirebase(FirebaseConfig firebase) {
this.firebase = firebase;
}
public ForwardConfig getForward() {
return forward;
}
public void setForward(ForwardConfig forward) {
this.forward = forward;
}
public InvitationConfig getInvite() {
return invite;
}
public void setInvite(InvitationConfig invite) {
this.invite = invite;
}
public KeyConfig getKey() {
return key;
}
public void setKey(KeyConfig key) {
this.key = key;
}
public GenericLdapConfig getLdap() {
return ldap;
}
public void setLdap(GenericLdapConfig ldap) {
this.ldap = ldap;
}
public Lookup getLookup() {
return lookup;
}
public void setLookup(Lookup lookup) {
this.lookup = lookup;
}
public MatrixConfig getMatrix() {
return matrix;
}
public void setMatrix(MatrixConfig matrix) {
this.matrix = matrix;
}
public MemoryStoreConfig getMemory() {
return memory;
}
public void setMemory(MemoryStoreConfig memory) {
this.memory = memory;
}
public NotificationConfig getNotification() {
return notification;
}
public void setNotification(NotificationConfig notification) {
this.notification = notification;
}
public NetIqLdapConfig getNetiq() {
return netiq;
}
public void setNetiq(NetIqLdapConfig netiq) {
this.netiq = netiq;
}
public ServerConfig getServer() {
return server;
}
public void setServer(ServerConfig server) {
this.server = server;
}
public SessionConfig getSession() {
return session;
}
public void setSession(SessionConfig session) {
this.session = session;
}
public StorageConfig getStorage() {
return storage;
}
public void setStorage(StorageConfig storage) {
this.storage = storage;
}
public RestBackendConfig getRest() {
return rest;
}
public void setRest(RestBackendConfig rest) {
this.rest = rest;
}
public GenericSqlProviderConfig getSql() {
return sql;
}
public void setSql(GenericSqlProviderConfig sql) {
this.sql = sql;
}
public SynapseSqlProviderConfig getSynapseSql() {
return synapseSql;
}
public void setSynapseSql(SynapseSqlProviderConfig synapseSql) {
this.synapseSql = synapseSql;
}
public ViewConfig getView() {
return view;
}
public void setView(ViewConfig view) {
this.view = view;
}
public WordpressConfig getWordpress() {
return wordpress;
}
public void setWordpress(WordpressConfig wordpress) {
this.wordpress = wordpress;
}
public MxisdConfig build() {
if (StringUtils.isBlank(getServer().getName())) {
getServer().setName(getMatrix().getDomain());
log.debug("server.name is empty, using matrix.domain");
}
getAuth().build();
getDirectory().build();
getExec().build();
getFirebase().build();
getForward().build();
getInvite().build();
getKey().build();
getLdap().build();
getLookup().build();
getMatrix().build();
getMemory().build();
getNetiq().build();
getNotification().build();
getRest().build();
getSession().build();
getServer().build();
getSql().build();
getStorage().build();
getSynapseSql().build();
getView().build();
getWordpress().build();
return this;
}
}

View File

@@ -22,18 +22,14 @@ package io.kamax.mxisd.config;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Configuration
@ConfigurationProperties(prefix = "lookup.recursive.bridge")
public class RecursiveLookupBridgeConfig { public class RecursiveLookupBridgeConfig {
private Logger log = LoggerFactory.getLogger(RecursiveLookupBridgeConfig.class); private transient final Logger log = LoggerFactory.getLogger(RecursiveLookupBridgeConfig.class);
private boolean enabled; private boolean enabled;
private boolean recursiveOnly; private boolean recursiveOnly;

View File

@@ -20,18 +20,14 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.ArrayList;
import org.springframework.context.annotation.Configuration;
import java.util.List; import java.util.List;
@Configuration
@ConfigurationProperties(prefix = "lookup.recursive")
public class RecursiveLookupConfig { public class RecursiveLookupConfig {
private boolean enabled; private boolean enabled;
private List<String> allowedCidr; private List<String> allowedCidr = new ArrayList<>();
private RecursiveLookupBridgeConfig bridge; private RecursiveLookupBridgeConfig bridge = new RecursiveLookupBridgeConfig();
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return enabled;
@@ -57,4 +53,8 @@ public class RecursiveLookupConfig {
this.bridge = bridge; this.bridge = bridge;
} }
public void build() {
// no-op
}
} }

View File

@@ -20,11 +20,6 @@
package io.kamax.mxisd.config; 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 { public class SQLiteStorageConfig {
private String database; private String database;

View File

@@ -23,25 +23,17 @@ package io.kamax.mxisd.config;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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; import javax.annotation.PostConstruct;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
@Configuration
@ConfigurationProperties(prefix = "server")
public class ServerConfig { public class ServerConfig {
private Logger log = LoggerFactory.getLogger(ServerConfig.class); private transient final Logger log = LoggerFactory.getLogger(ServerConfig.class);
@Autowired
private MatrixConfig mxCfg;
private String name; private String name;
private int port; private int port = 8090;
private String publicUrl; private String publicUrl;
public String getName() { public String getName() {
@@ -72,11 +64,6 @@ public class ServerConfig {
public void build() { public void build() {
log.info("--- Server config ---"); log.info("--- Server config ---");
if (StringUtils.isBlank(getName())) {
setName(mxCfg.getDomain());
log.debug("server.name is empty, using matrix.domain");
}
if (StringUtils.isBlank(getPublicUrl())) { if (StringUtils.isBlank(getPublicUrl())) {
setPublicUrl("https://" + getName()); setPublicUrl("https://" + getName());
log.debug("Public URL is empty, generating from name"); log.debug("Public URL is empty, generating from name");

View File

@@ -23,17 +23,12 @@ package io.kamax.mxisd.config;
import com.google.gson.Gson; import com.google.gson.Gson;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("session")
public class SessionConfig { public class SessionConfig {
private static Logger log = LoggerFactory.getLogger(SessionConfig.class); private transient final Logger log = LoggerFactory.getLogger(SessionConfig.class);
public static class Policy { public static class Policy {
@@ -144,18 +139,8 @@ public class SessionConfig {
} }
private MatrixConfig mxCfg;
private Policy policy = new Policy(); private Policy policy = new Policy();
@Autowired
public SessionConfig(MatrixConfig mxCfg) {
this.mxCfg = mxCfg;
}
public MatrixConfig getMatrixCfg() {
return mxCfg;
}
public Policy getPolicy() { public Policy getPolicy() {
return policy; return policy;
} }

View File

@@ -22,16 +22,27 @@ package io.kamax.mxisd.config;
import io.kamax.mxisd.exception.ConfigurationException; import io.kamax.mxisd.exception.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("storage")
public class StorageConfig { public class StorageConfig {
private String backend; public static class Provider {
private SQLiteStorageConfig sqlite = new SQLiteStorageConfig();
public SQLiteStorageConfig getSqlite() {
return sqlite;
}
public void setSqlite(SQLiteStorageConfig sqlite) {
this.sqlite = sqlite;
}
}
private String backend = "sqlite";
private Provider provider = new Provider();
public String getBackend() { public String getBackend() {
return backend; return backend;
@@ -41,8 +52,16 @@ public class StorageConfig {
this.backend = backend; this.backend = backend;
} }
public Provider getProvider() {
return provider;
}
public void setProvider(Provider provider) {
this.provider = provider;
}
@PostConstruct @PostConstruct
private void postConstruct() { public void build() {
if (StringUtils.isBlank(getBackend())) { if (StringUtils.isBlank(getBackend())) {
throw new ConfigurationException("storage.backend"); throw new ConfigurationException("storage.backend");
} }

View File

@@ -20,19 +20,15 @@
package io.kamax.mxisd.config; package io.kamax.mxisd.config;
import com.google.gson.Gson; import io.kamax.matrix.json.GsonUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("view")
public class ViewConfig { public class ViewConfig {
private Logger log = LoggerFactory.getLogger(ViewConfig.class); private transient final Logger log = LoggerFactory.getLogger(ViewConfig.class);
public static class Session { public static class Session {
@@ -138,7 +134,7 @@ public class ViewConfig {
@PostConstruct @PostConstruct
public void build() { public void build() {
log.info("--- View config ---"); log.info("--- View config ---");
log.info("Session: {}", new Gson().toJson(session)); log.info("Session: {}", GsonUtil.get().toJson(session));
} }
} }

View File

@@ -0,0 +1,42 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sàrl
*
* https://www.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.matrix.json.GsonUtil;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.representer.Representer;
import java.io.FileInputStream;
import java.io.IOException;
public class YamlConfigLoader {
public static MxisdConfig loadFromFile(String path) throws IOException {
Representer rep = new Representer();
rep.getPropertyUtils().setAllowReadOnlyProperties(true);
rep.getPropertyUtils().setSkipMissingProperties(true);
Yaml yaml = new Yaml(new Constructor(MxisdConfig.class), rep);
Object o = yaml.load(new FileInputStream(path));
return GsonUtil.get().fromJson(GsonUtil.get().toJson(o), MxisdConfig.class);
}
}

View File

@@ -259,7 +259,7 @@ public abstract class LdapConfig {
} }
private Logger log = LoggerFactory.getLogger(LdapConfig.class); private transient final Logger log = LoggerFactory.getLogger(LdapConfig.class);
private boolean enabled; private boolean enabled;
private String filter; private String filter;

View File

@@ -21,13 +21,7 @@
package io.kamax.mxisd.config.ldap.generic; package io.kamax.mxisd.config.ldap.generic;
import io.kamax.mxisd.config.ldap.LdapConfig; import io.kamax.mxisd.config.ldap.LdapConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
@ConfigurationProperties(prefix = "ldap")
@Primary
public class GenericLdapConfig extends LdapConfig { public class GenericLdapConfig extends LdapConfig {
@Override @Override

View File

@@ -21,11 +21,7 @@
package io.kamax.mxisd.config.ldap.netiq; package io.kamax.mxisd.config.ldap.netiq;
import io.kamax.mxisd.config.ldap.LdapConfig; import io.kamax.mxisd.config.ldap.LdapConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "netiq")
public class NetIqLdapConfig extends LdapConfig { public class NetIqLdapConfig extends LdapConfig {
@Override @Override

View File

@@ -20,12 +20,9 @@
package io.kamax.mxisd.config.memory; package io.kamax.mxisd.config.memory;
import org.springframework.stereotype.Component;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@Component
public class MemoryIdentityConfig { public class MemoryIdentityConfig {
private String username; private String username;

View File

@@ -20,17 +20,13 @@
package io.kamax.mxisd.config.memory; package io.kamax.mxisd.config.memory;
import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.ArrayList;
import org.springframework.context.annotation.Configuration;
import java.util.List; import java.util.List;
@Configuration
@ConfigurationProperties("memory")
public class MemoryStoreConfig { public class MemoryStoreConfig {
private boolean enabled; private boolean enabled;
private List<MemoryIdentityConfig> identities; private List<MemoryIdentityConfig> identities = new ArrayList<>();
public boolean isEnabled() { public boolean isEnabled() {
return enabled; return enabled;
@@ -48,4 +44,8 @@ public class MemoryStoreConfig {
this.identities = identities; this.identities = identities;
} }
public void build() {
// no-op
}
} }

View File

@@ -21,9 +21,7 @@
package io.kamax.mxisd.config.memory; package io.kamax.mxisd.config.memory;
import io.kamax.matrix._ThreePid; import io.kamax.matrix._ThreePid;
import org.springframework.stereotype.Component;
@Component
public class MemoryThreePid implements _ThreePid { public class MemoryThreePid implements _ThreePid {
private String medium; private String medium;

View File

@@ -24,8 +24,6 @@ import io.kamax.mxisd.exception.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.net.MalformedURLException; import java.net.MalformedURLException;
@@ -33,8 +31,6 @@ import java.net.URL;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@Configuration
@ConfigurationProperties("rest")
public class RestBackendConfig { public class RestBackendConfig {
public static class IdentityEndpoints { public static class IdentityEndpoints {
@@ -133,7 +129,7 @@ public class RestBackendConfig {
} }
private Logger log = LoggerFactory.getLogger(RestBackendConfig.class); private transient final Logger log = LoggerFactory.getLogger(RestBackendConfig.class);
private boolean enabled; private boolean enabled;
private String host; private String host;

View File

@@ -24,14 +24,13 @@ import io.kamax.mxisd.util.GsonUtil;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import javax.annotation.PostConstruct;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
public abstract class SqlConfig { public abstract class SqlConfig {
private transient Logger log = LoggerFactory.getLogger(SqlConfig.class); private transient final Logger log = LoggerFactory.getLogger(SqlConfig.class);
public static class Query { public static class Query {
@@ -283,7 +282,6 @@ public abstract class SqlConfig {
protected abstract String getProviderName(); protected abstract String getProviderName();
@PostConstruct
public void build() { public void build() {
if (getAuth().isEnabled() == null) { if (getAuth().isEnabled() == null) {
getAuth().setEnabled(isEnabled()); getAuth().setEnabled(isEnabled());

View File

@@ -21,13 +21,7 @@
package io.kamax.mxisd.config.sql.generic; package io.kamax.mxisd.config.sql.generic;
import io.kamax.mxisd.config.sql.SqlConfig; import io.kamax.mxisd.config.sql.SqlConfig;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
@Configuration
@ConfigurationProperties("sql")
@Primary
public class GenericSqlProviderConfig extends SqlConfig { public class GenericSqlProviderConfig extends SqlConfig {
@Override @Override

View File

@@ -23,13 +23,7 @@ package io.kamax.mxisd.config.sql.synapse;
import io.kamax.mxisd.backend.sql.synapse.SynapseQueries; import io.kamax.mxisd.backend.sql.synapse.SynapseQueries;
import io.kamax.mxisd.config.sql.SqlConfig; import io.kamax.mxisd.config.sql.SqlConfig;
import org.apache.commons.lang.StringUtils; 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("synapseSql")
public class SynapseSqlProviderConfig extends SqlConfig { public class SynapseSqlProviderConfig extends SqlConfig {
@Override @Override
@@ -37,8 +31,9 @@ public class SynapseSqlProviderConfig extends SqlConfig {
return "Synapse SQL"; return "Synapse SQL";
} }
@PostConstruct public void build() {
public void doBuild() { super.build();
getAuth().setEnabled(false); // Synapse does the auth, we only act as a directory/identity service. getAuth().setEnabled(false); // Synapse does the auth, we only act as a directory/identity service.
// FIXME check that the DB is not the mxisd one // FIXME check that the DB is not the mxisd one

View File

@@ -24,15 +24,11 @@ import io.kamax.mxisd.util.GsonUtil;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Configuration
@ConfigurationProperties("notification.handlers.sendgrid")
public class EmailSendGridConfig { public class EmailSendGridConfig {
public static class EmailTemplate { public static class EmailTemplate {
@@ -172,7 +168,7 @@ public class EmailSendGridConfig {
} }
private Logger log = LoggerFactory.getLogger(EmailSendGridConfig.class); private transient final Logger log = LoggerFactory.getLogger(EmailSendGridConfig.class);
private Api api = new Api(); private Api api = new Api();
private Identity identity = new Identity(); private Identity identity = new Identity();

View File

@@ -23,16 +23,12 @@ package io.kamax.mxisd.config.threepid.connector;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties(prefix = "threepid.medium.email.connectors.smtp")
public class EmailSmtpConfig { public class EmailSmtpConfig {
private Logger log = LoggerFactory.getLogger(EmailSmtpConfig.class); private transient final Logger log = LoggerFactory.getLogger(EmailSmtpConfig.class);
private String host; private String host;
private int port; private int port;

View File

@@ -22,18 +22,14 @@ package io.kamax.mxisd.config.threepid.connector;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties(prefix = PhoneTwilioConfig.NAMESPACE)
public class PhoneTwilioConfig { public class PhoneTwilioConfig {
static final String NAMESPACE = "threepid.medium.msisdn.connectors.twilio"; static final String NAMESPACE = "threepid.medium.msisdn.connectors.twilio";
private Logger log = LoggerFactory.getLogger(PhoneTwilioConfig.class); private transient final Logger log = LoggerFactory.getLogger(PhoneTwilioConfig.class);
private String accountSid; private String accountSid;
private String authToken; private String authToken;

View File

@@ -26,18 +26,11 @@ import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils; import org.apache.commons.lang.WordUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; 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; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("threepid.medium.email")
public class EmailConfig { public class EmailConfig {
private Logger log = LoggerFactory.getLogger(EmailConfig.class);
public static class Identity { public static class Identity {
private String from; private String from;
private String name; private String name;
@@ -60,13 +53,14 @@ public class EmailConfig {
} }
private transient final Logger log = LoggerFactory.getLogger(EmailConfig.class);
private String generator; private String generator;
private String connector; private String connector;
private MatrixConfig mxCfg; private MatrixConfig mxCfg;
private Identity identity = new Identity(); private Identity identity = new Identity();
@Autowired
public EmailConfig(MatrixConfig mxCfg) { public EmailConfig(MatrixConfig mxCfg) {
this.mxCfg = mxCfg; this.mxCfg = mxCfg;
} }

View File

@@ -22,16 +22,12 @@ package io.kamax.mxisd.config.threepid.medium;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("threepid.medium.email.generators.template")
public class EmailTemplateConfig extends GenericTemplateConfig { public class EmailTemplateConfig extends GenericTemplateConfig {
private static Logger log = LoggerFactory.getLogger(EmailTemplateConfig.class); private transient final Logger log = LoggerFactory.getLogger(EmailTemplateConfig.class);
@PostConstruct @PostConstruct
public void build() { public void build() {

View File

@@ -24,16 +24,12 @@ import io.kamax.mxisd.exception.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("threepid.medium.msisdn")
public class PhoneConfig { public class PhoneConfig {
private Logger log = LoggerFactory.getLogger(PhoneConfig.class); private transient final Logger log = LoggerFactory.getLogger(PhoneConfig.class);
private String generator; private String generator;
private String connector; private String connector;

View File

@@ -22,16 +22,12 @@ package io.kamax.mxisd.config.threepid.medium;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
@Configuration
@ConfigurationProperties("threepid.medium.msisdn.generators.template")
public class PhoneSmsTemplateConfig extends GenericTemplateConfig { public class PhoneSmsTemplateConfig extends GenericTemplateConfig {
private static Logger log = LoggerFactory.getLogger(EmailTemplateConfig.class); private transient final Logger log = LoggerFactory.getLogger(EmailTemplateConfig.class);
@PostConstruct @PostConstruct
public void build() { public void build() {

View File

@@ -20,22 +20,20 @@
package io.kamax.mxisd.config.threepid.notification; package io.kamax.mxisd.config.threepid.notification;
import com.google.gson.JsonObject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@Configuration
@ConfigurationProperties("notification")
public class NotificationConfig { public class NotificationConfig {
private Logger log = LoggerFactory.getLogger(NotificationConfig.class); private transient final Logger log = LoggerFactory.getLogger(NotificationConfig.class);
private Map<String, String> handler = new HashMap<>(); private Map<String, String> handler = new HashMap<>();
private Map<String, JsonObject> handlers = new HashMap<>();
public Map<String, String> getHandler() { public Map<String, String> getHandler() {
return handler; return handler;
@@ -45,13 +43,19 @@ public class NotificationConfig {
this.handler = handler; this.handler = handler;
} }
public Map<String, JsonObject> getHandlers() {
return handlers;
}
public void setHandlers(Map<String, JsonObject> handlers) {
this.handlers = handlers;
}
@PostConstruct @PostConstruct
public void build() { public void build() {
log.info("--- Notification config ---"); log.info("--- Notification config ---");
log.info("Handlers:"); log.info("Handlers:");
handler.forEach((k, v) -> { handler.forEach((k, v) -> log.info("\t{}: {}", k, v));
log.info("\t{}: {}", k, v);
});
} }
} }

View File

@@ -22,14 +22,10 @@ package io.kamax.mxisd.config.wordpress;
import io.kamax.mxisd.exception.ConfigurationException; import io.kamax.mxisd.exception.ConfigurationException;
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct; import javax.annotation.PostConstruct;
import java.util.Map; import java.util.Map;
@Configuration
@ConfigurationProperties("wordpress")
public class WordpressConfig { public class WordpressConfig {
public static class Credential { public static class Credential {

View File

@@ -1,144 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.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;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import io.kamax.mxisd.exception.*;
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();
private String handle(HttpServletRequest req, String erroCode, String error) {
JsonObject obj = new JsonObject();
obj.addProperty("errcode", erroCode);
obj.addProperty("error", error);
obj.addProperty("success", false);
log.info("Request {} {} - Error {}: {}", req.getMethod(), req.getRequestURL(), erroCode, error);
return gson.toJson(obj);
}
@ExceptionHandler(RemoteLoginException.class)
public String handle(HttpServletRequest request, HttpServletResponse response, RemoteLoginException e) {
if (e.getErrorBodyMsgResp() != null) {
response.setStatus(e.getStatus());
log.info("Request {} {} - Error {}: {}", request.getMethod(), request.getRequestURL(), e.getErrorCode(), e.getError());
return gson.toJson(e.getErrorBodyMsgResp());
}
return handleGeneric(request, response, e);
}
@ExceptionHandler(InternalServerError.class)
public String handle(HttpServletRequest request, HttpServletResponse response, InternalServerError e) {
if (StringUtils.isNotBlank(e.getInternalReason())) {
log.error("Reference #{} - {}", e.getReference(), e.getInternalReason());
} else {
log.error("Reference #{}", e);
}
return handleGeneric(request, response, e);
}
@ExceptionHandler(FeatureNotAvailable.class)
public String handle(HttpServletRequest request, HttpServletResponse response, FeatureNotAvailable e) {
if (StringUtils.isNotBlank(e.getInternalReason())) {
log.error("Feature not available: {}", e.getInternalReason());
}
return handleGeneric(request, response, e);
}
@ExceptionHandler(HttpMatrixException.class)
public String handleGeneric(HttpServletRequest request, HttpServletResponse response, HttpMatrixException e) {
response.setStatus(e.getStatus());
return handle(request, e.getErrorCode(), e.getError());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MissingServletRequestParameterException.class)
public String handle(HttpServletRequest req, MissingServletRequestParameterException e) {
return handle(req, "M_INCOMPLETE_REQUEST", e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(InvalidResponseJsonException.class)
public String handle(HttpServletRequest req, InvalidResponseJsonException e) {
return handle(req, "M_INVALID_JSON", e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(JsonSyntaxException.class)
public String handle(HttpServletRequest req, JsonSyntaxException e) {
return handle(req, "M_INVALID_JSON", e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(JsonMemberNotFoundException.class)
public String handle(HttpServletRequest req, JsonMemberNotFoundException e) {
return handle(req, "M_JSON_MISSING_KEYS", e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(MappingAlreadyExistsException.class)
public String handle(HttpServletRequest req, MappingAlreadyExistsException e) {
return handle(req, "M_ALREADY_EXISTS", e.getMessage());
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(BadRequestException.class)
public String handle(HttpServletRequest req, BadRequestException e) {
return handle(req, "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(
req,
"M_UNKNOWN",
StringUtils.defaultIfBlank(
e.getMessage(),
"An internal server error occurred. If this error persists, please contact support with reference #" +
Instant.now().toEpochMilli()
)
);
}
}

View File

@@ -1,104 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2018 Kamax Sarl
*
* https://www.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.app.v1;
import io.kamax.matrix.json.GsonUtil;
import io.kamax.mxisd.as.AppServiceHandler;
import io.kamax.mxisd.config.ListenerConfig;
import io.kamax.mxisd.exception.HttpMatrixException;
import io.kamax.mxisd.exception.NotAllowedException;
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.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.PUT;
@RestController
@CrossOrigin
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class AppServiceController {
private final Logger log = LoggerFactory.getLogger(AppServiceController.class);
private final ListenerConfig cfg;
private final String notFoundBody;
private final AppServiceHandler handler;
@Autowired
public AppServiceController(ListenerConfig cfg, AppServiceHandler handler) {
this.notFoundBody = GsonUtil.get().toJson(GsonUtil.makeObj("errcode", "io.kamax.mxisd.AS_NOT_FOUND"));
this.cfg = cfg;
this.handler = handler;
}
private void validateToken(String token) {
if (StringUtils.isBlank(token)) {
throw new HttpMatrixException(401, "M_UNAUTHORIZED", "No HS token");
}
if (!StringUtils.equals(cfg.getToken().getHs(), token)) {
throw new NotAllowedException("Invalid HS token");
}
}
@RequestMapping(value = "/rooms/**", method = GET)
public String getRoom(HttpServletResponse res, @RequestParam(name = "access_token", required = false) String token) {
validateToken(token);
res.setStatus(404);
return notFoundBody;
}
@RequestMapping(value = "/users/**", method = GET)
public String getUser(HttpServletResponse res, @RequestParam(name = "access_token", required = false) String token) {
validateToken(token);
res.setStatus(404);
return notFoundBody;
}
@RequestMapping(value = "/transactions/{txnId:.+}", method = PUT)
public CompletableFuture<String> getTransaction(
HttpServletRequest request,
@RequestParam(name = "access_token", required = false) String token,
@PathVariable String txnId
) {
validateToken(token);
try {
log.info("Received AS transaction {}", txnId);
return handler.processTransaction(txnId, request.getInputStream());
} catch (IOException e) {
throw new RuntimeException("AS Transaction " + txnId + ": I/O error when getting input", e);
}
}
}

View File

@@ -1,124 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.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.auth.v1;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import io.kamax.mxisd.auth.AuthManager;
import io.kamax.mxisd.auth.UserAuthResult;
import io.kamax.mxisd.controller.auth.v1.io.CredentialsValidationResponse;
import io.kamax.mxisd.exception.JsonMemberNotFoundException;
import io.kamax.mxisd.util.GsonParser;
import io.kamax.mxisd.util.GsonUtil;
import org.apache.commons.io.IOUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
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 javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
@RestController
@CrossOrigin
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public class AuthController {
// TODO export into SDK
private static final String logV1Url = "/_matrix/client/r0/login";
private Logger log = LoggerFactory.getLogger(AuthController.class);
private Gson gson = GsonUtil.build();
private GsonParser parser = new GsonParser(gson);
@Autowired
private AuthManager mgr;
@Autowired
private CloseableHttpClient client;
@RequestMapping(value = "/_matrix-internal/identity/v1/check_credentials", method = RequestMethod.POST)
public String checkCredentials(HttpServletRequest req) {
try {
JsonObject authData = parser.parse(req.getInputStream(), "user");
if (!authData.has("id") || !authData.has("password")) {
throw new JsonMemberNotFoundException("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);
CredentialsValidationResponse response = new CredentialsValidationResponse(result.isSuccess());
if (result.isSuccess()) {
response.setDisplayName(result.getDisplayName());
response.getProfile().setThreePids(result.getThreePids());
}
JsonElement authObj = gson.toJsonTree(response);
JsonObject obj = new JsonObject();
obj.add("auth", authObj);
obj.add("authentication", authObj); // TODO remove later, legacy support
return gson.toJson(obj);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@RequestMapping(value = logV1Url, method = RequestMethod.GET)
public String getLogin(HttpServletRequest req, HttpServletResponse res) {
URI target = URI.create(req.getRequestURL().toString());
try (CloseableHttpResponse hsResponse = client.execute(new HttpGet(mgr.resolveProxyUrl(target)))) {
res.setStatus(hsResponse.getStatusLine().getStatusCode());
return EntityUtils.toString(hsResponse.getEntity());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@RequestMapping(value = logV1Url, method = RequestMethod.POST)
public String login(HttpServletRequest req) {
URI target = URI.create(req.getRequestURL().toString());
try {
return mgr.proxyLogin(target, IOUtils.toString(req.getInputStream(), StandardCharsets.UTF_8));
} catch (IOException e) {
log.error("Unable to read input data from client");
throw new RuntimeException(e);
}
}
}

View File

@@ -1,61 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.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.directory.v1;
import com.google.gson.Gson;
import io.kamax.mxisd.controller.ProxyController;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchRequest;
import io.kamax.mxisd.controller.directory.v1.io.UserDirectorySearchResult;
import io.kamax.mxisd.directory.DirectoryManager;
import io.kamax.mxisd.util.GsonParser;
import io.kamax.mxisd.util.GsonUtil;
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.net.URI;
@RestController
@CrossOrigin
@RequestMapping(path = "/_matrix/client/r0/user_directory", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class UserDirectoryController extends ProxyController {
private Gson gson = GsonUtil.build();
private GsonParser parser = new GsonParser(gson);
@Autowired
private DirectoryManager mgr;
@RequestMapping(path = "/search", method = RequestMethod.POST)
public String search(HttpServletRequest request) throws IOException {
String accessToken = getAccessToken(request);
UserDirectorySearchRequest searchQuery = parser.parse(request, UserDirectorySearchRequest.class);
URI target = URI.create(request.getRequestURL().toString());
UserDirectorySearchResult result = mgr.search(target, accessToken, searchQuery.getSearchTerm());
return gson.toJson(result);
}
}

View File

@@ -1,82 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.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.identity.v1;
import com.google.gson.Gson;
import io.kamax.matrix.MatrixID;
import io.kamax.matrix.crypto.KeyManager;
import io.kamax.mxisd.config.ServerConfig;
import io.kamax.mxisd.controller.identity.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 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;
import java.util.HashMap;
import java.util.Map;
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);
@Autowired
private InvitationManager mgr;
@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(MatrixID.asAcceptable(sender), medium, address, roomId, parameters);
IThreePidInviteReply reply = mgr.storeInvite(invite);
return gson.toJson(new ThreePidInviteReplyIO(reply, keyMgr.getPublicKeyBase64(keyMgr.getCurrentIndex()), srvCfg.getPublicUrl()));
}
}

View File

@@ -1,81 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.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.identity.v1;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.kamax.matrix.crypto.KeyManager;
import io.kamax.mxisd.controller.identity.v1.io.KeyValidityJson;
import io.kamax.mxisd.exception.BadRequestException;
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.*;
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)
public class KeyController {
private Logger log = LoggerFactory.getLogger(KeyController.class);
@Autowired
private KeyManager keyMgr;
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)
public 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);
JsonObject obj = new JsonObject();
obj.addProperty("public_key", keyMgr.getPublicKeyBase64(keyId));
return gson.toJson(obj);
}
@RequestMapping(value = "/pubkey/ephemeral/isvalid", method = GET)
public String checkEphemeralKeyValidity(HttpServletRequest request) {
log.warn("Ephemeral key was requested but no ephemeral key are generated, replying not valid");
return invalidKey;
}
@RequestMapping(value = "/pubkey/isvalid", method = GET)
public String checkKeyValidity(HttpServletRequest request, @RequestParam("public_key") String pubKey) {
log.info("Validating public key {}", pubKey);
// TODO do in manager
boolean valid = StringUtils.equals(pubKey, keyMgr.getPublicKeyBase64(keyMgr.getCurrentIndex()));
return valid ? validKey : invalidKey;
}
}

View File

@@ -1,134 +0,0 @@
/*
* mxisd - Matrix Identity Server Daemon
* Copyright (C) 2017 Kamax Sarl
*
* https://www.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.identity.v1;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import io.kamax.matrix.crypto.SignatureManager;
import io.kamax.matrix.event.EventKey;
import io.kamax.matrix.json.MatrixJson;
import io.kamax.mxisd.config.MatrixConfig;
import io.kamax.mxisd.controller.identity.v1.io.SingeLookupReplyJson;
import io.kamax.mxisd.exception.InternalServerError;
import io.kamax.mxisd.lookup.*;
import io.kamax.mxisd.lookup.strategy.LookupStrategy;
import io.kamax.mxisd.util.GsonParser;
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;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
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)
public class MappingController {
private Logger log = LoggerFactory.getLogger(MappingController.class);
private Gson gson = new Gson();
private GsonParser parser = new GsonParser(gson);
@Autowired
private MatrixConfig mxCfg;
@Autowired
private LookupStrategy strategy;
@Autowired
private SignatureManager signMgr;
private void setRequesterInfo(ALookupRequest lookupReq, HttpServletRequest req) {
lookupReq.setRequester(req.getRemoteAddr());
String xff = req.getHeader("X-FORWARDED-FOR");
log.debug("XFF header: {}", xff);
lookupReq.setRecursive(StringUtils.isBlank(xff));
if (!lookupReq.isRecursive()) {
lookupReq.setRecurseHosts(Arrays.asList(xff.split(",")));
lookupReq.setRequester(lookupReq.getRecurseHosts().get(lookupReq.getRecurseHosts().size() - 1));
}
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();
setRequesterInfo(lookupRequest, request);
lookupRequest.setType(medium);
lookupRequest.setThreePid(address);
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 "{}";
}
SingleLookupReply lookup = lookupOpt.get();
// FIXME signing should be done in the business model, not in the controller
JsonObject obj = gson.toJsonTree(new SingeLookupReplyJson(lookup)).getAsJsonObject();
obj.add(EventKey.Signatures.get(), signMgr.signMessageGson(MatrixJson.encodeCanonical(obj)));
return gson.toJson(obj);
}
@RequestMapping(value = "/bulk_lookup", method = POST)
String bulkLookup(HttpServletRequest request) {
BulkLookupRequest lookupRequest = new BulkLookupRequest();
setRequesterInfo(lookupRequest, request);
log.info("Got bulk lookup request from {} with client {} - Is recursive? {}", lookupRequest.getRequester(), lookupRequest.getUserAgent(), lookupRequest.isRecursive());
try {
ClientBulkLookupRequest input = parser.parse(request, ClientBulkLookupRequest.class);
List<ThreePidMapping> mappings = new ArrayList<>();
for (List<String> mappingRaw : input.getThreepids()) {
ThreePidMapping mapping = new ThreePidMapping();
mapping.setMedium(mappingRaw.get(0));
mapping.setValue(mappingRaw.get(1));
mappings.add(mapping);
}
lookupRequest.setMappings(mappings);
ClientBulkLookupAnswer answer = new ClientBulkLookupAnswer();
answer.addAll(strategy.find(lookupRequest));
return gson.toJson(answer);
} catch (IOException e) {
throw new InternalServerError(e);
}
}
}

Some files were not shown because too many files have changed in this diff Show More