Java Code Examples for io.kamax.matrix.MatrixID#asAcceptable()

The following examples show how to use io.kamax.matrix.MatrixID#asAcceptable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmailNotificationTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void forThreepidInvite() throws MessagingException, IOException {
    String registerUrl = "https://" + RandomStringUtils.randomAlphanumeric(20) + ".example.org/register";
    gm.setUser(user, user);

    _MatrixID sender = MatrixID.asAcceptable(user, domain);
    ThreePidInvite inv = new ThreePidInvite(sender, ThreePidMedium.Email.getId(), target, "!rid:" + domain);
    inv.getProperties().put(PlaceholderNotificationGenerator.RegisterUrl, registerUrl);
    m.getNotif().sendForReply(new ThreePidInviteReply("a", inv, "b", "c", new ArrayList<>()));

    assertEquals(1, gm.getReceivedMessages().length);
    MimeMessage msg = gm.getReceivedMessages()[0];
    assertEquals(1, msg.getFrom().length);
    assertEquals(senderNameEncoded, msg.getFrom()[0].toString());
    assertEquals(1, msg.getRecipients(Message.RecipientType.TO).length);

    // We just check on the text/plain one. HTML is multipart and it's difficult so we skip
    MimeMultipart content = (MimeMultipart) msg.getContent();
    MimeBodyPart mbp = (MimeBodyPart) content.getBodyPart(0);
    String mbpContent = mbp.getContent().toString();
    assertTrue(mbpContent.contains(registerUrl));
}
 
Example 2
Source File: SessionManager.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public SingleLookupReply bind(String sid, String secret, String mxidRaw) {
    // We make sure we have an acceptable User ID
    if (StringUtils.isEmpty(mxidRaw)) {
        throw new IllegalArgumentException("No Matrix User ID provided");
    }

    // We ensure the session was validated
    ThreePidSession session = getSessionIfValidated(sid, secret);

    // We parse the Matrix ID as acceptable
    _MatrixID mxid = MatrixID.asAcceptable(mxidRaw);

    // Only accept binds if the domain matches our own
    if (!StringUtils.equalsIgnoreCase(mxCfg.getDomain(), mxid.getDomain())) {
        throw new NotAllowedException("Only Matrix IDs from domain " + mxCfg.getDomain() + " can be bound");
    }

    log.info("Session {}: Binding of {}:{} to Matrix ID {} is accepted",
            session.getId(), session.getThreePid().getMedium(), session.getThreePid().getAddress(), mxid.getId());

    SingleLookupRequest request = new SingleLookupRequest();
    request.setType(session.getThreePid().getMedium());
    request.setThreePid(session.getThreePid().getAddress());
    return new SingleLookupReply(request, mxid);
}
 
Example 3
Source File: EmailNotificationTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void forMatrixIdInvite() throws MessagingException {
    gm.setUser("mxisd", "mxisd");

    _MatrixID sender = MatrixID.asAcceptable(user, domain);
    _MatrixID recipient = MatrixID.asAcceptable(notifiee, domain);
    MatrixIdInvite idInvite = new MatrixIdInvite(
            "!rid:" + domain,
            sender,
            recipient,
            ThreePidMedium.Email.getId(),
            target,
            Collections.emptyMap()
    );

    m.getNotif().sendForInvite(idInvite);

    assertEquals(1, gm.getReceivedMessages().length);
    MimeMessage msg = gm.getReceivedMessages()[0];
    assertEquals(1, msg.getFrom().length);
    assertEquals(senderNameEncoded, msg.getFrom()[0].toString());
    assertEquals(1, msg.getRecipients(Message.RecipientType.TO).length);
}
 
Example 4
Source File: SingleLookupReply.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
public static SingleLookupReply fromRecursive(SingleLookupRequest request, String body) {
    SingleLookupReply reply = new SingleLookupReply();
    reply.isRecursive = true;
    reply.request = request;
    reply.body = body;

    try {
        SingeLookupReplyJson json = gson.fromJson(body, SingeLookupReplyJson.class);
        reply.mxid = MatrixID.asAcceptable(json.getMxid());
        reply.notAfter = Instant.ofEpochMilli(json.getNot_after());
        reply.notBefore = Instant.ofEpochMilli(json.getNot_before());
        reply.timestamp = Instant.ofEpochMilli(json.getTs());
        reply.signatures = new HashMap<>(json.getSignatures());
    } catch (JsonSyntaxException e) {
        // stub - we only want to try, nothing more
    }

    return reply;
}
 
Example 5
Source File: SignEd25519Handler.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    JsonObject body = parseJsonObject(exchange);

    _MatrixID mxid = MatrixID.asAcceptable(GsonUtil.getStringOrThrow(body, "mxid"));
    String token = GsonUtil.getStringOrThrow(body, "token");
    String privKey = GsonUtil.getStringOrThrow(body, "private_key");

    IThreePidInviteReply reply = invMgr.getInvite(token, privKey);
    _MatrixID sender = reply.getInvite().getSender();

    JsonObject res = new JsonObject();
    res.addProperty("token", token);
    res.addProperty("sender", sender.getId());
    res.addProperty("mxid", mxid.getId());
    res.add("signatures", signMgr.signMessageGson(cfg.getServer().getName(), MatrixJson.encodeCanonical(res)));

    log.info("Signed data for invite using token {}", token);
    respondJson(exchange, res);
}
 
Example 6
Source File: StoreInviteHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    String reqContentType = getContentType(exchange).orElse("application/octet-stream");
    JsonObject invJson = new JsonObject();

    if (StringUtils.startsWith(reqContentType, "application/json")) {
        invJson = parseJsonObject(exchange);
    }

    // Backward compatibility for pre-r0.1.0 implementations
    else if (StringUtils.startsWith(reqContentType, "application/x-www-form-urlencoded")) {
        String body = getBodyUtf8(exchange);
        Map<String, Deque<String>> parms = QueryParameterUtils.parseQueryString(body, StandardCharsets.UTF_8.name());
        for (Map.Entry<String, Deque<String>> entry : parms.entrySet()) {
            if (entry.getValue().size() == 0) {
                return;
            }

            if (entry.getValue().size() > 1) {
                throw new BadRequestException("key " + entry.getKey() + " has more than one value");
            }

            invJson.addProperty(entry.getKey(), entry.getValue().peekFirst());
        }
    } else {
        throw new BadRequestException("Unsupported Content-Type: " + reqContentType);
    }

    Type parmType = new TypeToken<Map<String, String>>() {
    }.getType();
    Map<String, String> parameters = GsonUtil.get().fromJson(invJson, parmType);
    StoreInviteRequest inv = GsonUtil.get().fromJson(invJson, StoreInviteRequest.class);
    _MatrixID sender = MatrixID.asAcceptable(inv.getSender());

    IThreePidInvite invite = new ThreePidInvite(sender, inv.getMedium(), inv.getAddress(), inv.getRoomId(), parameters);
    IThreePidInviteReply reply = invMgr.storeInvite(invite);

    // FIXME the key info must be set by the invitation manager in the reply object!
    respondJson(exchange, new ThreePidInviteReplyIO(reply, keyMgr.getPublicKeyBase64(keyMgr.getServerSigningKey().getId()), cfg.getPublicUrl()));
}
 
Example 7
Source File: RestThreePidProvider.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
private _MatrixID getMxId(UserID id) {
    if (UserIdType.Localpart.is(id.getType())) {
        return MatrixID.asAcceptable(id.getValue(), mxCfg.getDomain());
    } else {
        return MatrixID.asAcceptable(id.getValue());
    }
}
 
Example 8
Source File: ExecIdentityStore.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
private _MatrixID getUserId(UserID id) {
    if (Objects.isNull(id)) {
        throw new JsonParseException("User id key is not present");
    }

    if (UserIdType.Localpart.is(id.getType())) {
        return MatrixID.asAcceptable(id.getValue(), mxCfg.getDomain());
    }

    if (UserIdType.MatrixID.is(id.getType())) {
        return MatrixID.asAcceptable(id.getValue());
    }

    throw new InternalServerError("Unknown user type: " + id.getType());
}
 
Example 9
Source File: InvitationManager.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
private InvitationConfig requireValid(MxisdConfig cfg) {
    // This is not configured, we'll apply a default configuration
    if (Objects.isNull(cfg.getInvite().getExpiration().isEnabled())) {
        // We compute our own user, so it can be used if we bridge as well
        String mxId = MatrixID.asAcceptable("_mxisd-expired_invite", cfg.getMatrix().getDomain()).getId();

        // Enabled by default
        cfg.getInvite().getExpiration().setEnabled(true);
    }

    if (cfg.getInvite().getExpiration().isEnabled()) {
        if (cfg.getInvite().getExpiration().getAfter() < 1) {
            throw new ConfigurationException("Invitation expiration delay must be greater or equal to 1");
        }

        if (StringUtils.isBlank(cfg.getInvite().getExpiration().getResolveTo())) {
            String localpart = cfg.getAppsvc().getUser().getInviteExpired();
            if (StringUtils.isBlank(localpart)) {
                throw new ConfigurationException("Could not compute the Invitation expiration resolution target from App service user: not set");
            }

            cfg.getInvite().getExpiration().setResolveTo(MatrixID.asAcceptable(localpart, cfg.getMatrix().getDomain()).getId());
        }

        try {
            MatrixID.asAcceptable(cfg.getInvite().getExpiration().getResolveTo());
        } catch (IllegalArgumentException e) {
            throw new ConfigurationException("Invitation expiration resolution target is not a valid Matrix ID: " + e.getMessage());
        }
    }

    return cfg.getInvite();
}
 
Example 10
Source File: MatrixJsonPersistentEvent.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public MatrixJsonPersistentEvent(JsonObject obj) {
    super(obj);

    id = getString("event_id");
    type = getString("type");
    time = getLong("origin_server_ts");
    age = getInt("age", -1);
    sender = MatrixID.asAcceptable(getString("sender"));
}
 
Example 11
Source File: ProfileHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    String userId = getQueryParameter(exchange, UserID);
    _MatrixID mxId = MatrixID.asAcceptable(userId);
    URI target = URI.create(exchange.getRequestURL());
    Optional<String> accessTokenOpt = findAccessToken(exchange);

    HttpGet reqOut = new HttpGet(target);
    accessTokenOpt.ifPresent(accessToken -> reqOut.addHeader(headerName, headerValuePrefix + accessToken));

    Response res = mgr.enhance(mxId, reqOut);
    respond(exchange, res);
}
 
Example 12
Source File: InternalProfileHandler.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleRequest(HttpServerExchange exchange) {
    String userId = getQueryParameter(exchange, UserID);
    _MatrixID mxId = MatrixID.asAcceptable(userId);
    URI target = URI.create(exchange.getRequestURI());
    Optional<String> accessTokenOpt = findAccessToken(exchange);

    HttpGet reqOut = new HttpGet(target);
    accessTokenOpt.ifPresent(accessToken -> reqOut.addHeader(headerName, headerValuePrefix + accessToken));

    respond(exchange, GsonUtil.makeObj("roles", GsonUtil.asArray(mgr.getRoles(mxId))));
}
 
Example 13
Source File: SessionManager.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
public void unbind(JsonObject reqData) {
    _MatrixID mxid;
    try {
        mxid = MatrixID.asAcceptable(GsonUtil.getStringOrThrow(reqData, "mxid"));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }

    String sid = GsonUtil.getStringOrNull(reqData, "sid");
    String secret = GsonUtil.getStringOrNull(reqData, "client_secret");
    ThreePid tpid = GsonUtil.get().fromJson(GsonUtil.getObj(reqData, "threepid"), ThreePid.class);

    // We ensure the session was validated
    ThreePidSession session = getSessionIfValidated(sid, secret);

    // As per spec, we can only allow if the provided 3PID matches the validated session
    if (!session.getThreePid().equals(tpid)) {
        throw new BadRequestException("3PID to unbind does not match the one from the validated session");
    }

    // We only allow unbind for the domain we manage, mirroring bind
    if (!StringUtils.equalsIgnoreCase(mxCfg.getDomain(), mxid.getDomain())) {
        throw new NotAllowedException("Only Matrix IDs from domain " + mxCfg.getDomain() + " can be unbound");
    }

    log.info("Session {}: Unbinding of {}:{} to Matrix ID {} is accepted",
            session.getId(), session.getThreePid().getMedium(), session.getThreePid().getAddress(), mxid.getId());
}
 
Example 14
Source File: ReceiptsEventParsingTest.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void parseReceiptEvent() {
    _MatrixEvent event = MatrixJsonEventFactory.get(GsonUtil.parseObj(getJson()));

    assertThat(event, instanceOf(MatrixJsonReadReceiptEvent.class));

    List<MatrixJsonReadReceiptEvent.Receipt> receipts = ((MatrixJsonReadReceiptEvent) event).getReceipts();

    Map<String, Map<MatrixID, Long>> receiptsMap = receipts.stream()
            .collect(Collectors.toMap(it -> it.getEventId(), it -> it.getUsersWithTimestamp()));

    String id1 = "$15296836321000niTzS:matrix.localtoast.de";
    String id2 = "$1520971505455BCXJZ:matrix.localtoast.de";

    Set<String> ids = receiptsMap.keySet();
    assertThat(ids.size(), is(2));
    assertTrue(ids.contains(id1));
    assertTrue(ids.contains(id2));

    MatrixID matrixId1a = MatrixID.asAcceptable("@caldavtestuser:matrix.localtoast.de");
    MatrixID matrixId1b = MatrixID.asAcceptable("@arne:matrix.localtoast.de");
    MatrixID matrixId2 = MatrixID.asAcceptable("@arne:testmatrix.localtoast.de");

    assertThat(receiptsMap.get(id1).get(matrixId1a), is(1529683638046L));
    assertThat(receiptsMap.get(id1).get(matrixId1b), is(1531668885573L));
    assertThat(receiptsMap.get(id2).get(matrixId2), is(1520971518671L));
}
 
Example 15
Source File: MembershipEventProcessor.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public void process(JsonObject ev, _MatrixID sender, String roomId) {
    JsonObject content = EventKey.Content.findObj(ev).orElseGet(() -> {
        log.debug("No content found, falling back to full object");
        return ev;
    });

    String targetId = EventKey.StateKey.getStringOrNull(ev);
    if (StringUtils.isBlank(targetId)) {
        log.warn("Invalid event: No invitee ID, skipping");
        return;
    }

    _MatrixID target = MatrixID.asAcceptable(targetId);
    if (!StringUtils.equals(target.getDomain(), cfg.getMatrix().getDomain())) {
        log.debug("Ignoring invite for {}: not a local user", targetId);
        return;
    }

    log.info("Got membership event from {} to {} for room {}", sender.getId(), targetId, roomId);

    boolean isForMainUser = StringUtils.equals(target.getLocalPart(), cfg.getAppsvc().getUser().getMain());
    boolean isForExpInvUser = StringUtils.equals(target.getLocalPart(), cfg.getAppsvc().getUser().getInviteExpired());

    if (StringUtils.equals("join", EventKey.Membership.getStringOrNull(content))) {
        if (isForExpInvUser) {
            log.warn("We joined the room {} for another identity as the main user, which is not supported. Leaving...", roomId);

            client.getUser(target.getLocalPart()).getRoom(roomId).tryLeave().ifPresent(err -> {
                log.warn("Could not decline invite to room {}: {} - {}", roomId, err.getErrcode(), err.getError());
            });
        }
    } else if (StringUtils.equals("invite", EventKey.Membership.getStringOrNull(content))) {
        if (isForMainUser) {
            processForMainUser(roomId, sender);
        } else if (isForExpInvUser) {
            processForExpiredInviteUser(roomId, target);
        } else {
            processForUserIdInvite(roomId, sender, target);
        }
    } else if (StringUtils.equals("leave", EventKey.Membership.getStringOrNull(content))) {
        // TODO we need to find out if this is only us remaining and leave the room if so, using the right client for it
    } else {
        log.debug("This is not an supported type of membership event, skipping");
    }
}
 
Example 16
Source File: RoomInviteHandler.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
@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);
}
 
Example 17
Source File: SingleLookupReply.java    From mxisd with GNU Affero General Public License v3.0 4 votes vote down vote up
public SingleLookupReply(SingleLookupRequest request, String mxid) {
    this(request, MatrixID.asAcceptable(mxid));
}