Search in sources :

Example 1 with GsonParser

use of io.kamax.mxisd.util.GsonParser in project mxisd by kamax-io.

the class SessionMananger method createRemote.

public IThreePidSession createRemote(String sid, String secret) {
    ThreePidSession session = getSessionIfValidated(sid, secret);
    log.info("Creating remote 3PID session for {} with local session [{}] to {}", session.getThreePid(), sid);
    boolean isLocal = isLocal(session.getThreePid());
    PolicySource policy = cfg.getPolicy().getValidation().forIf(isLocal);
    if (!policy.isEnabled() || !policy.toRemote()) {
        throw new NotAllowedException("Validating " + (isLocal ? "local" : "remote") + " 3PID is not allowed");
    }
    log.info("Remote 3PID is allowed by policy");
    List<String> servers = mxCfg.getIdentity().getServers(policy.getToRemote().getServer());
    if (servers.isEmpty()) {
        throw new FeatureNotAvailable("Remote 3PID sessions are enabled but server list is " + "misconstrued (invalid ID or empty list");
    }
    String is = servers.get(0);
    String url = IdentityServerUtils.findIsUrlForDomain(is).orElseThrow(() -> new InternalServerError(is + " could not be resolved to an Identity server"));
    log.info("Will use IS endpoint {}", url);
    String remoteSecret = session.isRemote() ? session.getRemoteSecret() : RandomStringUtils.randomAlphanumeric(16);
    JsonObject body = new JsonObject();
    body.addProperty("client_secret", remoteSecret);
    body.addProperty(session.getThreePid().getMedium(), session.getThreePid().getAddress());
    body.addProperty("send_attempt", session.increaseAndGetRemoteAttempt());
    if (ThreePidMedium.PhoneNumber.is(session.getThreePid().getMedium())) {
        try {
            Phonenumber.PhoneNumber msisdn = phoneUtil.parse("+" + session.getThreePid().getAddress(), null);
            String country = phoneUtil.getRegionCodeForNumber(msisdn).toUpperCase();
            body.addProperty("phone_number", phoneUtil.format(msisdn, PhoneNumberUtil.PhoneNumberFormat.NATIONAL));
            body.addProperty("country", country);
        } catch (NumberParseException e) {
            throw new InternalServerError(e);
        }
    } else {
        body.addProperty(session.getThreePid().getMedium(), session.getThreePid().getAddress());
    }
    log.info("Requesting remote session with attempt {}", session.getRemoteAttempt());
    HttpPost tokenReq = RestClientUtils.post(url + "/_matrix/identity/api/v1/validate/" + session.getThreePid().getMedium() + "/requestToken", body);
    try (CloseableHttpResponse response = client.execute(tokenReq)) {
        int status = response.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            JsonObject obj = parser.parseOptional(response).orElseThrow(() -> new RemoteIdentityServerException("Status " + status));
            throw new RemoteIdentityServerException(obj.get("errcode").getAsString() + ": " + obj.get("error").getAsString());
        }
        RequestTokenResponse data = new GsonParser().parse(response, RequestTokenResponse.class);
        log.info("Remote Session ID: {}", data.getSid());
        session.setRemoteData(url, data.getSid(), remoteSecret, 1);
        storage.updateThreePidSession(session.getDao());
        log.info("Updated Session {} with remote data", sid);
        return session;
    } catch (IOException e) {
        log.warn("Failed to create remote session with {} for {}: {}", url, session.getThreePid(), e.getMessage());
        throw new RemoteIdentityServerException(e.getMessage());
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) JsonObject(com.google.gson.JsonObject) RequestTokenResponse(io.kamax.mxisd.controller.identity.v1.io.RequestTokenResponse) IOException(java.io.IOException) ThreePidSession(io.kamax.mxisd.threepid.session.ThreePidSession) IThreePidSession(io.kamax.mxisd.threepid.session.IThreePidSession) GsonParser(io.kamax.mxisd.util.GsonParser) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) NumberParseException(com.google.i18n.phonenumbers.NumberParseException) PolicySource(io.kamax.mxisd.config.SessionConfig.Policy.PolicyTemplate.PolicySource) Phonenumber(com.google.i18n.phonenumbers.Phonenumber)

Example 2 with GsonParser

use of io.kamax.mxisd.util.GsonParser in project mxisd by kamax-io.

the class SessionMananger method submitRemote.

private void submitRemote(ThreePidSession session, String token) {
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("sid", session.getRemoteId()), new BasicNameValuePair("client_secret", session.getRemoteSecret()), new BasicNameValuePair("token", token)), StandardCharsets.UTF_8);
    HttpPost submitReq = new HttpPost(session.getRemoteServer() + "/_matrix/identity/api/v1/submitToken");
    submitReq.setEntity(entity);
    try (CloseableHttpResponse response = client.execute(submitReq)) {
        JsonObject o = new GsonParser().parse(response.getEntity().getContent());
        if (!o.has("success") || !o.get("success").getAsBoolean()) {
            String errcode = o.get("errcode").getAsString();
            throw new RemoteIdentityServerException(errcode + ": " + o.get("error").getAsString());
        }
        log.info("Successfully submitted validation token for {} to {}", session.getThreePid(), session.getRemoteServer());
    } catch (IOException e) {
        throw new RemoteIdentityServerException(e.getMessage());
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) GsonParser(io.kamax.mxisd.util.GsonParser) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) JsonObject(com.google.gson.JsonObject) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException)

Example 3 with GsonParser

use of io.kamax.mxisd.util.GsonParser in project mxisd by kamax-io.

the class SessionMananger method validateRemote.

public void validateRemote(String sid, String secret) {
    ThreePidSession session = getSessionIfValidated(sid, secret);
    if (!session.isRemote()) {
        throw new NotAllowedException("Cannot remotely validate a local session");
    }
    log.info("Session {} for {}: Validating remote 3PID session {} on {}", sid, session.getThreePid(), session.getRemoteId(), session.getRemoteServer());
    if (session.isRemoteValidated()) {
        log.info("Session {} for {}: Already remotely validated", sid, session.getThreePid());
        return;
    }
    HttpGet validateReq = new HttpGet(session.getRemoteServer() + "/_matrix/identity/api/v1/3pid/getValidated3pid?sid=" + session.getRemoteId() + "&client_secret=" + session.getRemoteSecret());
    try (CloseableHttpResponse response = client.execute(validateReq)) {
        int status = response.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            throw new RemoteIdentityServerException("Remote identity server returned with status " + status);
        }
        JsonObject o = new GsonParser().parse(response.getEntity().getContent());
        if (o.has("errcode")) {
            String errcode = o.get("errcode").getAsString();
            if (StringUtils.equals("M_SESSION_NOT_VALIDATED", errcode)) {
                throw new SessionNotValidatedException();
            } else if (StringUtils.equals("M_NO_VALID_SESSION", errcode)) {
                throw new SessionUnknownException();
            } else {
                throw new RemoteIdentityServerException("Unknown error while validating Remote 3PID session: " + errcode + " - " + o.get("error").getAsString());
            }
        }
        if (o.has("validated_at")) {
            ThreePid remoteThreePid = new ThreePid(o.get("medium").getAsString(), o.get("address").getAsString());
            if (!session.getThreePid().equals(remoteThreePid)) {
                // sanity check
                throw new InternalServerError("Local 3PID " + session.getThreePid() + " and remote 3PID " + remoteThreePid + " do not match for session " + session.getId());
            }
            log.info("Session {} for {}: Remotely validated successfully", sid, session.getThreePid());
            session.validateRemote();
            storage.updateThreePidSession(session.getDao());
            log.info("Session {} was updated in storage", sid);
        }
    } catch (IOException e) {
        log.warn("Session {} for {}: Failed to validated remotely on {}: {}", sid, session.getThreePid(), session.getRemoteServer(), e.getMessage());
        throw new RemoteIdentityServerException(e.getMessage());
    }
}
Also used : HttpGet(org.apache.http.client.methods.HttpGet) JsonObject(com.google.gson.JsonObject) IOException(java.io.IOException) ThreePidSession(io.kamax.mxisd.threepid.session.ThreePidSession) IThreePidSession(io.kamax.mxisd.threepid.session.IThreePidSession) GsonParser(io.kamax.mxisd.util.GsonParser) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) ThreePid(io.kamax.matrix.ThreePid)

Aggregations

JsonObject (com.google.gson.JsonObject)3 GsonParser (io.kamax.mxisd.util.GsonParser)3 IOException (java.io.IOException)3 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)3 IThreePidSession (io.kamax.mxisd.threepid.session.IThreePidSession)2 ThreePidSession (io.kamax.mxisd.threepid.session.ThreePidSession)2 HttpPost (org.apache.http.client.methods.HttpPost)2 NumberParseException (com.google.i18n.phonenumbers.NumberParseException)1 Phonenumber (com.google.i18n.phonenumbers.Phonenumber)1 ThreePid (io.kamax.matrix.ThreePid)1 PolicySource (io.kamax.mxisd.config.SessionConfig.Policy.PolicyTemplate.PolicySource)1 RequestTokenResponse (io.kamax.mxisd.controller.identity.v1.io.RequestTokenResponse)1 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)1 HttpGet (org.apache.http.client.methods.HttpGet)1 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)1