use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.
the class RestProfileProvider method doRequest.
private <T> Optional<T> doRequest(_MatrixID userId, Function<RestBackendConfig.ProfileEndpoints, Optional<String>> endpoint, Function<JsonProfileResult, Optional<T>> value) {
Optional<String> url = endpoint.apply(cfg.getEndpoints().getProfile());
if (!url.isPresent()) {
return Optional.empty();
}
try {
URIBuilder builder = new URIBuilder(url.get());
HttpPost req = new HttpPost(builder.build());
req.setEntity(new StringEntity(GsonUtil.get().toJson(new JsonProfileRequest(userId)), ContentType.APPLICATION_JSON));
try (CloseableHttpResponse res = client.execute(req)) {
int sc = res.getStatusLine().getStatusCode();
if (sc == 404) {
log.info("Got 404 - No result found");
return Optional.empty();
}
if (sc != 200) {
throw new InternalServerError("Unexpected backed status code: " + sc);
}
String body = IOUtils.toString(res.getEntity().getContent(), StandardCharsets.UTF_8);
if (StringUtils.isBlank(body)) {
log.warn("Backend response body is empty/blank, expected JSON object with profile key");
return Optional.empty();
}
Optional<JsonObject> pJson = GsonUtil.findObj(GsonUtil.parseObj(body), "profile");
if (!pJson.isPresent()) {
log.warn("Backend response body is invalid, expected JSON object with profile key");
return Optional.empty();
}
JsonProfileResult profile = gson.fromJson(pJson.get(), JsonProfileResult.class);
return value.apply(profile);
}
} catch (JsonSyntaxException | InvalidJsonException e) {
log.error("Unable to parse backend response as JSON", e);
throw new InternalServerError(e);
} catch (URISyntaxException e) {
log.error("Unable to build a valid request URL", e);
throw new InternalServerError(e);
} catch (IOException e) {
log.error("I/O Error during backend request", e);
throw new InternalServerError();
}
}
use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.
the class SqlProfileProvider method getRoles.
@Override
public List<String> getRoles(_MatrixID user) {
log.info("Querying roles for {}", user.getId());
List<String> roles = new ArrayList<>();
String stmtSql = cfg.getRole().getQuery();
try (Connection conn = pool.get()) {
PreparedStatement stmt = conn.prepareStatement(stmtSql);
if (UserIdType.Localpart.is(cfg.getRole().getType())) {
setParameters(stmt, user.getLocalPart());
} else if (UserIdType.MatrixID.is(cfg.getRole().getType())) {
setParameters(stmt, user.getId());
} else {
throw new InternalServerError("Unsupported user type in SQL Role fetching: " + cfg.getRole().getType());
}
ResultSet rSet = stmt.executeQuery();
while (rSet.next()) {
String role = rSet.getString(1);
roles.add(role);
log.debug("Found role {}", role);
}
log.info("Got {} roles", roles.size());
return roles;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.
the class LdapDirectoryProvider method search.
protected UserDirectorySearchResult search(String query, List<String> attributes) {
UserDirectorySearchResult result = new UserDirectorySearchResult();
result.setLimited(false);
try (LdapConnection conn = getConn()) {
bind(conn);
LdapConfig.Attribute atCfg = getCfg().getAttribute();
attributes = new ArrayList<>(attributes);
attributes.add(getUidAtt());
String[] attArray = new String[attributes.size()];
attributes.toArray(attArray);
String searchQuery = buildOrQueryWithFilter(getCfg().getDirectory().getFilter(), "*" + query + "*", attArray);
log.debug("Query: {}", searchQuery);
log.debug("Attributes: {}", GsonUtil.build().toJson(attArray));
for (String baseDN : getBaseDNs()) {
log.debug("Base DN: {}", baseDN);
try (EntryCursor cursor = conn.search(baseDN, searchQuery, SearchScope.SUBTREE, attArray)) {
while (cursor.next()) {
Entry entry = cursor.get();
log.info("Found possible match, DN: {}", entry.getDn().getName());
getAttribute(entry, getUidAtt()).ifPresent(uid -> {
log.info("DN {} is a valid match", entry.getDn().getName());
try {
UserDirectorySearchResult.Result entryResult = new UserDirectorySearchResult.Result();
entryResult.setUserId(buildMatrixIdFromUid(uid));
getAttribute(entry, atCfg.getName()).ifPresent(entryResult::setDisplayName);
result.addResult(entryResult);
} catch (IllegalArgumentException e) {
log.warn("Bind was found but type {} is not supported", atCfg.getUid().getType());
}
});
}
}
}
} catch (CursorLdapReferralException e) {
log.warn("An entry is only available via referral, skipping");
} catch (IOException | LdapException | CursorException e) {
throw new InternalServerError(e);
}
return result;
}
use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.
the class RoomInviteHandler method handleRequest.
@Override
public void handleRequest(HttpServerExchange exchange) {
String accessToken = getAccessToken(exchange);
String whoamiUri = dns.transform(URI.create(exchange.getRequestURL()).resolve(URI.create("/_matrix/client/r0/account/whoami"))).toString();
log.info("Who Am I URL: {}", whoamiUri);
HttpGet whoAmIReq = new HttpGet(whoamiUri);
whoAmIReq.addHeader("Authorization", "Bearer " + accessToken);
_MatrixID uId;
try (CloseableHttpResponse whoAmIRes = client.execute(whoAmIReq)) {
int sc = whoAmIRes.getStatusLine().getStatusCode();
String body = EntityUtils.toString(whoAmIRes.getEntity());
if (sc != 200) {
log.warn("Unable to get caller identity from Homeserver - Status code: {}", sc);
log.debug("Body: {}", body);
throw new RemoteHomeServerException(body);
}
JsonObject json = GsonUtil.parseObj(body);
Optional<String> uIdRaw = GsonUtil.findString(json, "user_id");
if (!uIdRaw.isPresent()) {
throw new RemoteHomeServerException("No User ID provided when checking identity");
}
uId = MatrixID.asAcceptable(uIdRaw.get());
} catch (IOException e) {
InternalServerError ex = new InternalServerError(e);
log.error("Ref {}: Unable to fetch caller identity from Homeserver", ex.getReference());
throw ex;
}
log.info("Processing room invite from {}", uId.getId());
JsonObject reqBody = parseJsonObject(exchange);
if (!invMgr.canInvite(uId, reqBody)) {
throw new NotAllowedException("Your account is not allowed to invite that address");
}
log.info("Invite was allowing, relaying to the Homeserver");
proxyPost(exchange, reqBody, client, dns);
}
use of io.kamax.mxisd.exception.InternalServerError in project mxisd by kamax-io.
the class ClientDnsOverwrite method transform.
public URIBuilder transform(URI initial) {
URIBuilder builder = new URIBuilder(initial);
Entry mapping = mappings.get(initial.getHost());
if (mapping == null) {
throw new InternalServerError("No DNS client override for " + initial.getHost());
}
try {
URL target = new URL(mapping.getValue());
builder.setScheme(target.getProtocol());
builder.setHost(target.getHost());
if (target.getPort() != -1) {
builder.setPort(target.getPort());
}
return builder;
} catch (MalformedURLException e) {
log.warn("Skipping DNS overwrite entry {} due to invalid value [{}]: {}", mapping.getName(), mapping.getValue(), e.getMessage());
throw new ConfigurationException("Invalid DNS overwrite entry in homeserver client: " + mapping.getName(), e.getMessage());
}
}
Aggregations