Search in sources :

Example 6 with InternalServerError

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();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) JsonProfileRequest(io.kamax.mxisd.profile.JsonProfileRequest) JsonObject(com.google.gson.JsonObject) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) JsonSyntaxException(com.google.gson.JsonSyntaxException) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) InvalidJsonException(io.kamax.matrix.json.InvalidJsonException) JsonProfileResult(io.kamax.mxisd.profile.JsonProfileResult)

Example 7 with 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);
    }
}
Also used : SQLException(java.sql.SQLException) ArrayList(java.util.ArrayList) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 8 with InternalServerError

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;
}
Also used : EntryCursor(org.apache.directory.api.ldap.model.cursor.EntryCursor) IOException(java.io.IOException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) UserDirectorySearchResult(io.kamax.mxisd.http.io.UserDirectorySearchResult) LdapConfig(io.kamax.mxisd.config.ldap.LdapConfig) Entry(org.apache.directory.api.ldap.model.entry.Entry) CursorException(org.apache.directory.api.ldap.model.cursor.CursorException) CursorLdapReferralException(org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException) LdapException(org.apache.directory.api.ldap.model.exception.LdapException) UserDirectorySearchResult(io.kamax.mxisd.http.io.UserDirectorySearchResult) LdapConnection(org.apache.directory.ldap.client.api.LdapConnection)

Example 9 with InternalServerError

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);
}
Also used : RemoteHomeServerException(io.kamax.mxisd.exception.RemoteHomeServerException) NotAllowedException(io.kamax.mxisd.exception.NotAllowedException) HttpGet(org.apache.http.client.methods.HttpGet) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 10 with InternalServerError

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());
    }
}
Also used : Entry(io.kamax.mxisd.config.DnsOverwriteConfig.Entry) MalformedURLException(java.net.MalformedURLException) ConfigurationException(io.kamax.mxisd.exception.ConfigurationException) InternalServerError(io.kamax.mxisd.exception.InternalServerError) URL(java.net.URL) URIBuilder(org.apache.http.client.utils.URIBuilder)

Aggregations

InternalServerError (io.kamax.mxisd.exception.InternalServerError)24 IOException (java.io.IOException)13 LdapException (org.apache.directory.api.ldap.model.exception.LdapException)6 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)6 io.kamax.matrix._MatrixID (io.kamax.matrix._MatrixID)5 CursorException (org.apache.directory.api.ldap.model.cursor.CursorException)5 CursorLdapReferralException (org.apache.directory.api.ldap.model.cursor.CursorLdapReferralException)5 EntryCursor (org.apache.directory.api.ldap.model.cursor.EntryCursor)5 Entry (org.apache.directory.api.ldap.model.entry.Entry)5 JsonObject (com.google.gson.JsonObject)4 ThreePid (io.kamax.matrix.ThreePid)4 UserDirectorySearchResult (io.kamax.mxisd.http.io.UserDirectorySearchResult)4 Connection (java.sql.Connection)4 PreparedStatement (java.sql.PreparedStatement)4 ResultSet (java.sql.ResultSet)4 SQLException (java.sql.SQLException)4 ArrayList (java.util.ArrayList)4 LdapConnection (org.apache.directory.ldap.client.api.LdapConnection)4 MatrixID (io.kamax.matrix.MatrixID)3 GsonUtil (io.kamax.matrix.json.GsonUtil)3