io.kamax.matrix.MatrixID Java Examples

The following examples show how to use io.kamax.matrix.MatrixID. 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: LdapAuthTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void multiDNs() {
    MatrixConfig mxCfg = new MatrixConfig();
    mxCfg.setDomain(domain);
    mxCfg.build();

    LdapConfig cfg = new GenericLdapConfig();
    cfg.getConnection().setHost(host);
    cfg.getConnection().setPort(65001);
    cfg.getConnection().setBaseDNs(dnList);
    cfg.getConnection().setBindDn(mxisdCn);
    cfg.getConnection().setBindPassword(mxisdPw);

    LdapConfig.UID uid = new LdapConfig.UID();
    uid.setType(idType);
    uid.setValue(idAttribute);
    cfg.getAttribute().setUid(uid);
    cfg.build();

    LdapAuthProvider p = new LdapAuthProvider(cfg, mxCfg);
    BackendAuthResult result = p.authenticate(MatrixID.from(userId, domain).valid(), userPw);
    assertFalse(result.isSuccess());
}
 
Example #2
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 #3
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 #4
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 #5
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 #6
Source File: MatrixHttpTest.java    From matrix-java-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
protected InputStream readConfigFile() {
    InputStream configFile = this.getClass().getResourceAsStream("/HomeserverTest.conf");
    if (configFile != null) {
        try (BufferedReader buffer = new BufferedReader(new InputStreamReader(configFile))) {
            Map<String, String> configValues = buffer.lines()
                    .filter(line -> !line.startsWith("#") && !line.isEmpty()).collect(
                            Collectors.toMap(line -> line.split("=")[0].trim(), line -> line.split("=")[1].trim()));

            port = Integer.valueOf(configValues.get("Port"));
            hostname = configValues.get("Hostname");
            domain = configValues.get("Domain");
            baseUrl = "https://" + hostname + ":" + port;
            username = configValues.get("Username");
            password = configValues.get("Password");
            user = new MatrixID(username, domain);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
    return configFile;
}
 
Example #7
Source File: RoomCreateWiremockTest.java    From matrix-java-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void createRoomWithNoOption() throws Exception {
    String roomId = "!roomId:" + domain;
    JsonObject resBody = new JsonObject();
    resBody.addProperty("room_id", roomId);
    String resBodyRaw = GsonUtil.get().toJson(resBody);
    stubFor(post(urlPathEqualTo("/_matrix/client/r0/createRoom"))
            .willReturn(aResponse().withStatus(200).withBody(resBodyRaw)));

    MatrixHomeserver hs = new MatrixHomeserver(domain, baseUrl);
    MatrixClientContext context = new MatrixClientContext(hs, MatrixID.asValid("@user:localhost"), "test");
    MatrixHttpClient client = new MatrixHttpClient(context);

    _MatrixRoom room = client.createRoom(RoomCreationOptions.none());
    assertTrue(StringUtils.equals(room.getAddress(), roomId));

    verify(postRequestedFor(urlPathEqualTo(syncPath)));
}
 
Example #8
Source File: MatrixHttpClientSyncWiremockTest.java    From matrix-java-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
@Override
public void getSeveralSync() throws Exception {
    stubFor(get(urlPathEqualTo(syncPath)).willReturn(aResponse().withStatus(200).withBody(getJson())));
    stubFor(get(urlPathEqualTo(syncPath)).withQueryParam("access_token", equalTo("test"))
            .withQueryParam("timeout", equalTo("0")).willReturn(aResponse().withStatus(200).withBody(getJson())));

    MatrixHomeserver hs = new MatrixHomeserver(domain, baseUrl);
    MatrixClientContext context = new MatrixClientContext(hs, MatrixID.asValid("@user:localhost"), "test");
    MatrixHttpClient client = new MatrixHttpClient(context);
    setClient(client);

    super.getSeveralSync();

    verify(getRequestedFor(urlPathEqualTo(syncPath)));
    verify(getRequestedFor(urlPathEqualTo(syncPath)).withQueryParam("timeout", equalTo("0")));
}
 
Example #9
Source File: RestDirectoryProvider.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
private UserDirectorySearchResult search(String by, String query) {
    UserDirectorySearchRequest request = new UserDirectorySearchRequest(query);
    request.setBy(by);
    try (CloseableHttpResponse httpResponse = client.execute(RestClientUtils.post(cfg.getEndpoints().getDirectory(), request))) {
        int status = httpResponse.getStatusLine().getStatusCode();
        if (status < 200 || status >= 300) {
            throw new InternalServerError("REST backend: Error: " + IOUtils.toString(httpResponse.getEntity().getContent(), StandardCharsets.UTF_8));
        }

        UserDirectorySearchResult response = parser.parse(httpResponse, UserDirectorySearchResult.class);
        for (UserDirectorySearchResult.Result result : response.getResults()) {
            result.setUserId(MatrixID.asAcceptable(result.getUserId(), mxCfg.getDomain()).getId());
        }

        return response;
    } catch (IOException e) {
        throw new InternalServerError("REST backend: I/O error: " + e.getMessage());
    }
}
 
Example #10
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 #11
Source File: RestDirectoryProviderTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void byNameFound() {
    stubFor(post(urlEqualTo(endpoint))
            .willReturn(aResponse()
                    .withHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType())
                    .withBody(byNameResponse)
            )
    );

    UserDirectorySearchResult result = p.searchByDisplayName(byNameSearch);
    assertTrue(!result.isLimited());
    assertEquals(1, result.getResults().size());
    UserDirectorySearchResult.Result entry = result.getResults().iterator().next();
    assertNotNull(entry);
    assertTrue(StringUtils.equals(byNameAvatar, entry.getAvatarUrl()));
    assertTrue(StringUtils.equals(byNameDisplay, entry.getDisplayName()));
    assertTrue(StringUtils.equals(MatrixID.asAcceptable(byNameId, domain).getId(), entry.getUserId()));

    verify(postRequestedFor(urlMatching(endpoint))
            .withHeader("Content-Type", containing(ContentType.APPLICATION_JSON.getMimeType()))
            .withRequestBody(equalTo(byNameRequest))
    );
}
 
Example #12
Source File: RestDirectoryProviderTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void byThreepidFound() {
    stubFor(post(urlEqualTo(endpoint))
            .willReturn(aResponse()
                    .withHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType())
                    .withBody(new String(byThreepidResponse.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8))
            )
    );

    UserDirectorySearchResult result = p.searchBy3pid(byThreepidSearch);
    assertTrue(!result.isLimited());
    assertEquals(1, result.getResults().size());
    UserDirectorySearchResult.Result entry = result.getResults().iterator().next();
    assertNotNull(entry);
    assertTrue(StringUtils.equals(byThreepidAvatar, entry.getAvatarUrl()));
    assertTrue(StringUtils.equals(byThreepidDisplay, entry.getDisplayName()));
    assertTrue(StringUtils.equals(MatrixID.asAcceptable(byThreepidId, domain).getId(), entry.getUserId()));

    verify(postRequestedFor(urlMatching(endpoint))
            .withHeader("Content-Type", containing(ContentType.APPLICATION_JSON.getMimeType()))
            .withRequestBody(equalTo(byThreepidRequest))
    );
}
 
Example #13
Source File: MatrixJsonReadReceiptEvent.java    From matrix-java-sdk with GNU Affero General Public License v3.0 6 votes vote down vote up
public MatrixJsonReadReceiptEvent(JsonObject obj) {
    super(obj);

    JsonObject content = getObj("content");
    List<String> eventIds = StreamSupport.stream(content.entrySet()).map(Map.Entry::getKey)
            .collect(Collectors.toList());

    receipts = StreamSupport.stream(eventIds).map(id -> {
        JsonObject targetEvent = content.getAsJsonObject(id);
        JsonObject mRead = targetEvent.getAsJsonObject("m.read");

        Map<MatrixID, Long> readMarkers = StreamSupport.stream(mRead.entrySet())
                .collect(Collectors.toMap(it -> MatrixID.asAcceptable(it.getKey()),
                        it -> GsonUtil.getLong(it.getValue().getAsJsonObject(), "ts")));
        return new Receipt(id, readMarkers);
    }).collect(Collectors.toList());
}
 
Example #14
Source File: LdapAuthTest.java    From mxisd with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
public void singleDn() {
    LdapConfig cfg = new GenericLdapConfig();
    cfg.getConnection().setHost(host);
    cfg.getConnection().setPort(65001);
    cfg.getConnection().setBaseDn(dnList.get(0));
    cfg.getConnection().setBindDn(mxisdCn);
    cfg.getConnection().setBindPassword(mxisdPw);
    cfg.build();

    LdapConfig.UID uid = new LdapConfig.UID();
    uid.setType(idType);
    uid.setValue(idAttribute);
    cfg.getAttribute().setUid(uid);

    MatrixConfig mxCfg = new MatrixConfig();
    mxCfg.setDomain(domain);
    mxCfg.build();

    LdapAuthProvider p = new LdapAuthProvider(cfg, mxCfg);
    BackendAuthResult result = p.authenticate(MatrixID.from(userId, domain).valid(), userPw);
    assertFalse(result.isSuccess());
}
 
Example #15
Source File: MemoryIdentityStore.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public UserDirectorySearchResult searchByDisplayName(String query) {
    return search(
            entry -> StringUtils.containsIgnoreCase(entry.getUsername(), query),
            entry -> {
                UserDirectorySearchResult.Result result = new UserDirectorySearchResult.Result();
                result.setUserId(MatrixID.from(entry.getUsername(), mxCfg.getDomain()).acceptable().getId());
                result.setDisplayName(entry.getUsername());
                return result;
            }
    );
}
 
Example #16
Source File: WordpressThreePidProvider.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
protected Optional<_MatrixID> find(ThreePid tpid) {
    String query = cfg.getSql().getQuery().getThreepid().get(tpid.getMedium());
    if (Objects.isNull(query)) {
        return Optional.empty();
    }

    try (Connection conn = wordpress.getConnection()) {
        PreparedStatement stmt = conn.prepareStatement(query);
        stmt.setString(1, tpid.getAddress());

        try (ResultSet rSet = stmt.executeQuery()) {
            while (rSet.next()) {
                String uid = rSet.getString("uid");
                log.info("Found match: {}", uid);
                try {
                    return Optional.of(MatrixID.from(uid, mxCfg.getDomain()).valid());
                } catch (IllegalArgumentException ex) {
                    log.warn("Ignoring match {} - Invalid characters for a Matrix ID", uid);
                }
            }

            log.info("No valid match found in Wordpress");
            return Optional.empty();
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #17
Source File: MemoryIdentityStore.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public UserDirectorySearchResult searchBy3pid(String query) {
    return search(
            entry -> entry.getThreepids().stream()
                    .anyMatch(tpid -> StringUtils.containsIgnoreCase(tpid.getAddress(), query)),
            entry -> {
                UserDirectorySearchResult.Result result = new UserDirectorySearchResult.Result();
                result.setUserId(MatrixID.from(entry.getUsername(), mxCfg.getDomain()).acceptable().getId());
                result.setDisplayName(entry.getUsername());
                return result;
            }
    );
}
 
Example #18
Source File: AppSvcManager.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
private void processTransaction(List<JsonObject> eventsJson) {
    log.info("Processing transaction events: start");

    eventsJson.forEach(ev -> {
        String evId = EventKey.Id.getStringOrNull(ev);
        if (StringUtils.isBlank(evId)) {
            log.warn("Event has no ID, skipping");
            log.debug("Event:\n{}", GsonUtil.getPrettyForLog(ev));
            return;
        }
        log.debug("Event {}: processing start", evId);

        String roomId = EventKey.RoomId.getStringOrNull(ev);
        if (StringUtils.isBlank(roomId)) {
            log.debug("Event has no room ID, skipping");
            return;
        }

        String senderId = EventKey.Sender.getStringOrNull(ev);
        if (StringUtils.isBlank(senderId)) {
            log.debug("Event has no sender ID, skipping");
            return;
        }
        _MatrixID sender = MatrixID.asAcceptable(senderId);
        log.debug("Sender: {}", senderId);

        String evType = StringUtils.defaultIfBlank(EventKey.Type.getStringOrNull(ev), "<EMPTY/MISSING>");
        EventTypeProcessor p = processors.get(evType);
        if (Objects.isNull(p)) {
            log.debug("No event processor for type {}, skipping", evType);
            return;
        }

        p.process(ev, sender, roomId);

        log.debug("Event {}: processing end", evId);
    });

    log.info("Processing transaction events: end");
}
 
Example #19
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 #20
Source File: MemoryIdentityStore.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    logger.info("Performing lookup {} of type {}", request.getThreePid(), request.getType());
    ThreePid req = new ThreePid(request.getType(), request.getThreePid());
    for (MemoryIdentityConfig id : cfg.getIdentities()) {
        for (MemoryThreePid threepid : id.getThreepids()) {
            if (req.equals(new ThreePid(threepid.getMedium(), threepid.getAddress()))) {
                return Optional.of(new SingleLookupReply(request, MatrixID.asAcceptable(id.getUsername(), mxCfg.getDomain())));
            }
        }
    }

    return Optional.empty();
}
 
Example #21
Source File: MemoryIdentityStore.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public BackendAuthResult authenticate(_MatrixID mxid, String password) {
    return findByUsername(mxid.getLocalPart()).map(id -> {
        if (!StringUtils.equals(id.getUsername(), mxid.getLocalPart())) {
            return BackendAuthResult.failure();
        } else {
            BackendAuthResult result = new BackendAuthResult();
            id.getThreepids().forEach(tpid -> result.withThreePid(new ThreePid(tpid.getMedium(), tpid.getAddress())));
            result.succeed(mxid.getId(), UserIdType.MatrixID.getId(), "");
            return result;
        }
    }).orElseGet(BackendAuthResult::failure);
}
 
Example #22
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 #23
Source File: ExecDirectoryStore.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
private UserDirectorySearchResult search(ExecConfig.Process cfg, UserDirectorySearchRequest request) {
    if (StringUtils.isEmpty(cfg.getCommand())) {
        return UserDirectorySearchResult.empty();
    }

    Processor<UserDirectorySearchResult> p = new Processor<>(cfg);

    p.addJsonInputTemplate(tokens -> new UserDirectorySearchRequest(tokens.getType(), tokens.getQuery()));
    p.addInputTemplate(PlainType, tokens -> tokens.getType() + System.lineSeparator() + tokens.getQuery());

    p.addTokenMapper(cfg.getToken().getType(), request::getBy);
    p.addTokenMapper(cfg.getToken().getQuery(), request::getSearchTerm);

    p.addSuccessMapper(JsonType, output -> {
        if (StringUtils.isBlank(output)) {
            return UserDirectorySearchResult.empty();
        }

        UserDirectorySearchResult response = GsonUtil.get().fromJson(output, UserDirectorySearchResult.class);
        for (UserDirectorySearchResult.Result result : response.getResults()) {
            result.setUserId(MatrixID.asAcceptable(result.getUserId(), mxCfg.getDomain()).getId());
        }
        return response;
    });
    p.withFailureDefault(output -> new UserDirectorySearchResult());

    return p.execute();
}
 
Example #24
Source File: SqlThreePidProvider.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Optional<SingleLookupReply> find(SingleLookupRequest request) {
    log.info("SQL lookup");
    String stmtSql = StringUtils.defaultIfBlank(cfg.getIdentity().getMedium().get(request.getType()), cfg.getIdentity().getQuery());
    log.info("SQL query: {}", stmtSql);
    try (Connection conn = pool.get()) {
        try (PreparedStatement stmt = conn.prepareStatement(stmtSql)) {
            stmt.setString(1, request.getType().toLowerCase());
            stmt.setString(2, request.getThreePid().toLowerCase());

            try (ResultSet rSet = stmt.executeQuery()) {
                while (rSet.next()) {
                    String uid = rSet.getString("uid");
                    log.info("Found match: {}", uid);
                    if (StringUtils.equals("uid", cfg.getIdentity().getType())) {
                        log.info("Resolving as localpart");
                        return Optional.of(new SingleLookupReply(request, MatrixID.asAcceptable(uid, mxCfg.getDomain())));
                    }
                    if (StringUtils.equals("mxid", cfg.getIdentity().getType())) {
                        log.info("Resolving as MXID");
                        return Optional.of(new SingleLookupReply(request, MatrixID.asAcceptable(uid)));
                    }

                    log.info("Identity type is unknown, skipping");
                }

                log.info("No match found in SQL");
                return Optional.empty();
            }
        }
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
 
Example #25
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 #26
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 #27
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 #28
Source File: MatrixJsonDirectEvent.java    From matrix-java-sdk with GNU Affero General Public License v3.0 5 votes vote down vote up
public MatrixJsonDirectEvent(JsonObject obj) {
    super(obj);

    if (!StringUtils.equals(Type, getType())) { // FIXME check should be done in the abstract class
        throw new InvalidJsonException("Type is not " + Type);
    }

    getObj("content").entrySet().forEach(entry -> {
        if (!entry.getValue().isJsonArray()) {
            throw new InvalidJsonException("Content key " + entry.getKey() + " is not an array");
        }
        _MatrixID id = MatrixID.asAcceptable(entry.getKey());
        mappings.put(id, GsonUtil.asList(entry.getValue().getAsJsonArray(), String.class));
    });
}
 
Example #29
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 #30
Source File: ExecIdentityStoreTest.java    From mxisd with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void singleSuccessData() {
    SingleLookupRequest req = new SingleLookupRequest();
    req.setType(ThreePidMedium.Email.getId());
    req.setThreePid(user1Email);

    Optional<SingleLookupReply> lookup = getStore("singleSuccessData").find(req);
    assertTrue(lookup.isPresent());
    SingleLookupReply reply = lookup.get();
    assertEquals(MatrixID.asAcceptable(user1Localpart, domain), reply.getMxid());
}