RosterIntegrationTest.java

  1. /**
  2.  *
  3.  * Copyright 2015-2024 Florian Schmaus, 2022-2024 Guus der Kinderen
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.jivesoftware.smack.roster;

  18. import static org.junit.jupiter.api.Assertions.assertEquals;
  19. import static org.junit.jupiter.api.Assertions.assertTrue;

  20. import java.util.Collection;
  21. import java.util.concurrent.TimeoutException;

  22. import org.jivesoftware.smack.StanzaListener;
  23. import org.jivesoftware.smack.filter.AndFilter;
  24. import org.jivesoftware.smack.filter.FromMatchesFilter;
  25. import org.jivesoftware.smack.filter.PresenceTypeFilter;
  26. import org.jivesoftware.smack.filter.StanzaTypeFilter;
  27. import org.jivesoftware.smack.packet.Presence;
  28. import org.jivesoftware.smack.packet.PresenceBuilder;
  29. import org.jivesoftware.smack.roster.packet.RosterPacket.ItemType;
  30. import org.jivesoftware.smack.util.Consumer;
  31. import org.jivesoftware.smack.util.StringUtils;

  32. import org.igniterealtime.smack.inttest.AbstractSmackIntegrationTest;
  33. import org.igniterealtime.smack.inttest.SmackIntegrationTestEnvironment;
  34. import org.igniterealtime.smack.inttest.annotations.SmackIntegrationTest;
  35. import org.igniterealtime.smack.inttest.annotations.SpecificationReference;
  36. import org.igniterealtime.smack.inttest.util.IntegrationTestRosterUtil;
  37. import org.igniterealtime.smack.inttest.util.ResultSyncPoint;
  38. import org.igniterealtime.smack.inttest.util.SimpleResultSyncPoint;
  39. import org.jxmpp.jid.BareJid;
  40. import org.jxmpp.jid.Jid;

  41. @SpecificationReference(document = "RFC6121")
  42. public class RosterIntegrationTest extends AbstractSmackIntegrationTest {

  43.     private final Roster rosterOne;
  44.     private final Roster rosterTwo;

  45.     public RosterIntegrationTest(SmackIntegrationTestEnvironment environment) {
  46.         super(environment);
  47.         rosterOne = Roster.getInstanceFor(conOne);
  48.         rosterTwo = Roster.getInstanceFor(conTwo);
  49.     }

  50.     @SmackIntegrationTest
  51.     public void subscribeRequestListenerTest() throws TimeoutException, Exception {
  52.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

  53.         final SubscribeListener subscribeListener = new SubscribeListener() {
  54.             @Override
  55.             public SubscribeAnswer processSubscribe(Jid from, Presence subscribeRequest) {
  56.                 if (from.equals(conOne.getUser().asBareJid())) {
  57.                     return SubscribeAnswer.Approve;
  58.                 }
  59.                 return SubscribeAnswer.Deny;
  60.             }
  61.         };
  62.         rosterTwo.addSubscribeListener(subscribeListener);

  63.         final String conTwosRosterName = "ConTwo " + testRunId;
  64.         final SimpleResultSyncPoint addedAndSubscribed = new SimpleResultSyncPoint();
  65.         final RosterListener rosterListener = new AbstractRosterListener() {
  66.             @Override
  67.             public void entriesAdded(Collection<Jid> addresses) {
  68.                 checkIfAddedAndSubscribed(addresses);
  69.             }
  70.             @Override
  71.             public void entriesUpdated(Collection<Jid> addresses) {
  72.                 checkIfAddedAndSubscribed(addresses);
  73.             }
  74.             private void checkIfAddedAndSubscribed(Collection<Jid> addresses) {
  75.                 for (Jid jid : addresses) {
  76.                     if (!jid.equals(conTwo.getUser().asBareJid())) {
  77.                         continue;
  78.                     }
  79.                     BareJid bareJid = conTwo.getUser().asBareJid();
  80.                     RosterEntry rosterEntry = rosterOne.getEntry(bareJid);
  81.                     if (rosterEntry == null) {
  82.                         addedAndSubscribed.signalFailure("Added/Updated entry was not for " + bareJid);
  83.                         return;
  84.                     }
  85.                     String name = rosterEntry.getName();
  86.                     if (StringUtils.isNullOrEmpty(name)) {
  87.                         addedAndSubscribed.signalFailure("Added/Updated entry without name");
  88.                         return;
  89.                     }
  90.                     if (!rosterEntry.getName().equals(conTwosRosterName)) {
  91.                         addedAndSubscribed.signalFailure("Added/Updated entry name does not match. Expected: " + conTwosRosterName + " but was: " + rosterEntry.getName());
  92.                         return;
  93.                     }
  94.                     if (!rosterEntry.getType().equals(ItemType.to)) {
  95.                         return;
  96.                     }
  97.                     addedAndSubscribed.signal();
  98.                 }
  99.             }
  100.         };

  101.         rosterOne.addRosterListener(rosterListener);

  102.         try {
  103.             rosterOne.createItemAndRequestSubscription(conTwo.getUser().asBareJid(), conTwosRosterName, null);
  104.             assertResult(addedAndSubscribed,
  105.                 "A roster entry for " + conTwo.getUser().asBareJid() + " using the name '" + conTwosRosterName +
  106.                 "' of type 'to' was expected to be added to the roster of " + conOne.getUser() + " (but it was not).");
  107.         }
  108.         finally {
  109.             rosterTwo.removeSubscribeListener(subscribeListener);
  110.             rosterOne.removeRosterListener(rosterListener);
  111.         }
  112.     }

  113.     /**
  114.      * Asserts that when a user sends out a presence subscription request, the server sends a roster push back to the
  115.      * user.
  116.      *
  117.      * @throws Exception when errors occur
  118.      */
  119.     @SmackIntegrationTest(section = "3.1.2", quote =
  120.         "After locally delivering or remotely routing the presence subscription request, the user's server MUST then " +
  121.         "send a roster push to all of the user's interested resources, containing the potential contact with a " +
  122.         "subscription state of \"none\" and with notation that the subscription is pending (via an 'ask' attribute " +
  123.         "whose value is \"subscribe\").")
  124.     public void testRosterPushAfterSubscriptionRequest() throws Exception {
  125.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);
  126.         rosterTwo.setSubscriptionMode(Roster.SubscriptionMode.manual); // prevents a race condition when asserting the captured roster entry.
  127.         final ResultSyncPoint<RosterEntry, Exception> added = new ResultSyncPoint<>();

  128.         final RosterListener rosterListener = new AbstractRosterListener() {
  129.             @Override
  130.             public void entriesAdded(Collection<Jid> addresses) {
  131.                 for (Jid jid : addresses) {
  132.                     if (!jid.equals(conTwo.getUser().asBareJid())) {
  133.                         continue;
  134.                     }
  135.                     final BareJid bareJid = conTwo.getUser().asBareJid();
  136.                     RosterEntry rosterEntry = rosterOne.getEntry(bareJid);
  137.                     added.signal(rosterEntry);
  138.                     return;
  139.                 }
  140.             }
  141.         };
  142.         rosterOne.addRosterListener(rosterListener);

  143.         final Presence subscribe = conOne.getStanzaFactory().buildPresenceStanza()
  144.                 .ofType(Presence.Type.subscribe)
  145.                 .to(conTwo.getUser().asBareJid())
  146.                 .build();

  147.         try {
  148.             conOne.sendStanza(subscribe);

  149.             final RosterEntry rosterEntry = assertResult(added, "Expected the server to send a roster push back to '" + conOne.getUser() + "' after they sent a presence subscription request to '" + conTwo.getUser().asBareJid() + "' (but the server did not).");
  150.             assertEquals(ItemType.none, rosterEntry.getType(), "Unexpected subscription type on roster push after '" + conOne.getUser() + "' sent a presence subscription request to '" + conTwo.getUser().asBareJid() + "'.");
  151.             assertTrue(rosterEntry.isSubscriptionPending(), "Missing 'ask=subscribe' attribute on roster push after '" + conOne.getUser() + "' sent a presence subscription request to '" + conTwo.getUser().asBareJid() + "'.");
  152.         } finally {
  153.             rosterTwo.setSubscriptionMode(Roster.getDefaultSubscriptionMode());
  154.             rosterOne.removeRosterListener(rosterListener);
  155.         }
  156.     }

  157.     /**
  158.      * Asserts that when a user sends out a presence subscription request to an entity for which the user does not have
  159.      * a pre-existing subscription, the server will deliver the subscription request to that entity.
  160.      *
  161.      * @throws Exception when errors occur
  162.      */
  163.     @SmackIntegrationTest(section = "3.1.3", quote =
  164.         "if there is at least one available resource associated with the contact when the subscription request is " +
  165.         "received by the contact's server, then the contact's server MUST send that subscription request to all " +
  166.         "available resources in accordance with Section 8.")
  167.     public void testPresenceDeliveredToRecipient() throws Exception {
  168.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

  169.         final ResultSyncPoint<Presence, Exception> added = new ResultSyncPoint<>();
  170.         final StanzaListener stanzaListener = stanza -> added.signal((Presence) stanza);
  171.         conTwo.addAsyncStanzaListener(stanzaListener, new AndFilter(StanzaTypeFilter.PRESENCE, FromMatchesFilter.createBare(conOne.getUser())));

  172.         final Presence subscribe = conOne.getStanzaFactory().buildPresenceStanza()
  173.                 .ofType(Presence.Type.subscribe)
  174.                 .to(conTwo.getUser().asBareJid())
  175.                 .build();

  176.         try {
  177.             conOne.sendStanza(subscribe);
  178.             final Presence received = assertResult(added, "Expected subscription request from '" + conOne.getUser() + "' to '" + conTwo.getUser().asBareJid() + "' to be delivered to " + conTwo.getUser() + " (but it did not).");
  179.             assertEquals(Presence.Type.subscribe, received.getType(), "Unexpected presence type in presence stanza received by '" + conTwo.getUser() + "' after '" + conOne.getUser() + "' sent a presence subscription request.");
  180.         } finally {
  181.             conTwo.removeAsyncStanzaListener(stanzaListener);
  182.         }
  183.     }

  184.     /**
  185.      * Asserts that when a user sends a presence subscription approval, the server stamps the bare JID of the sender,
  186.      * and delivers it to the requester.
  187.      *
  188.      * @throws Exception when errors occur
  189.      */
  190.     @SmackIntegrationTest(section = "3.1.5", quote =
  191.         "When the contact's client sends the subscription approval, the contact's server MUST stamp the outbound " +
  192.         "stanza with the bare JID <contact@domainpart> of the contact and locally deliver or remotely route the " +
  193.         "stanza to the user.")
  194.     public void testPresenceApprovalStampedAndDelivered() throws Exception {
  195.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

  196.         rosterTwo.setSubscriptionMode(Roster.SubscriptionMode.accept_all);

  197.         // Modify the outbound 'subscribed' stanza, to be 'wrong' (addressed to a full rather than a bare JID), to test if the server overrides this.
  198.         final Consumer<PresenceBuilder> interceptor = (PresenceBuilder presenceBuilder) -> presenceBuilder.to(conOne.getUser()).build();
  199.         conTwo.addPresenceInterceptor(interceptor, p -> p.getType() == Presence.Type.subscribed);

  200.         final ResultSyncPoint<Presence, Exception> added = new ResultSyncPoint<>();
  201.         final StanzaListener stanzaListener = stanza -> added.signal((Presence) stanza);

  202.         conOne.addAsyncStanzaListener(stanzaListener, PresenceTypeFilter.SUBSCRIBED);

  203.         final Presence subscribe = conOne.getStanzaFactory().buildPresenceStanza()
  204.                 .ofType(Presence.Type.subscribe)
  205.                 .to(conTwo.getUser().asBareJid())
  206.                 .build();

  207.         try {
  208.             conOne.sendStanza(subscribe);

  209.             final Presence received = assertResult(added, "Expected presence 'subscribed' stanza to be delivered to '" + conOne.getUser() + "' after '" + conTwo.getUser() + "' approved their subscription request (but it was not).");
  210.             assertEquals(conTwo.getUser().asBareJid(), received.getFrom().asEntityBareJidOrThrow(), "Expected presence 'subscribed' stanza that was delivered to '" + conOne.getUser() + "' after '" + conTwo.getUser() + "' approved their subscription request to have a 'from' attribute value that is associated to '" + conTwo.getUser().getLocalpart() + "' (but it did not).");
  211.             assertTrue(received.getFrom().isEntityBareJid(), "Expected presence 'subscribed' stanza that was delivered to '" + conOne.getUser() + "' after '" + conTwo.getUser() + "' approved their subscription request to have a 'from' attribute value that is a bare JID (but it was not).");
  212.         } finally {
  213.             rosterTwo.setSubscriptionMode(Roster.getDefaultSubscriptionMode());
  214.             conTwo.removePresenceInterceptor(interceptor);
  215.             conOne.removeAsyncStanzaListener(stanzaListener);
  216.         }
  217.     }

  218.     /**
  219.      * Asserts that when a user sends a presence subscription approval, the server sends a roster push to the user with
  220.      * a subscription 'from'.
  221.      *
  222.      * @throws Exception when errors occur
  223.      */
  224.     @SmackIntegrationTest(section = "3.1.5", quote =
  225.         "The contact's server then MUST send an updated roster push to all of the contact's interested resources, " +
  226.         "with the 'subscription' attribute set to a value of \"from\".")
  227.     public void testPresenceApprovalYieldsRosterPush() throws Exception {
  228.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

  229.         rosterTwo.setSubscriptionMode(Roster.SubscriptionMode.accept_all);

  230.         final ResultSyncPoint<RosterEntry, Exception> updated = new ResultSyncPoint<>();

  231.         final RosterListener rosterListener = new AbstractRosterListener() {
  232.             @Override
  233.             public void entriesAdded(Collection<Jid> addresses) {
  234.                 for (Jid jid : addresses) {
  235.                     if (!jid.equals(conOne.getUser().asBareJid())) {
  236.                         continue;
  237.                     }
  238.                     BareJid bareJid = conOne.getUser().asBareJid();
  239.                     RosterEntry rosterEntry = rosterTwo.getEntry(bareJid);
  240.                     updated.signal(rosterEntry);
  241.                 }
  242.             }
  243.         };
  244.         rosterTwo.addRosterListener(rosterListener);

  245.         final Presence subscribe = conOne.getStanzaFactory().buildPresenceStanza()
  246.                 .ofType(Presence.Type.subscribe)
  247.                 .to(conTwo.getUser().asBareJid())
  248.                 .build();

  249.         try {
  250.             conOne.sendStanza(subscribe);
  251.             // The 'subscribe' gets automatically approved by conTwo.

  252.             final RosterEntry entry = assertResult(updated, "Expected '" + conTwo.getUser() + "' to receive a roster push with an update for the entry of '" + conOne.getUser().asBareJid() + "' after '" + conTwo.getUser() + "' approved their subscription request.");
  253.             assertEquals(ItemType.from, entry.getType(), "Unexpected type for '" + conOne.getUser().asBareJid() + "''s entry in '" + conTwo.getUser().asBareJid() + "''s roster.");
  254.         } finally {
  255.             rosterTwo.setSubscriptionMode(Roster.getDefaultSubscriptionMode());
  256.             rosterTwo.removeRosterListener(rosterListener);
  257.         }
  258.     }

  259.     /**
  260.      * Asserts that when a user sends a presence subscription approval, the server sends a roster push to the user with
  261.      * a subscription 'both' when the contact already has a subscription to the other entity.
  262.      *
  263.      * @throws Exception when errors occur
  264.      */
  265.     @SmackIntegrationTest(section = "3.1.5", quote =
  266.         "The contact's server then MUST send an updated roster push to all of the contact's interested resources, " +
  267.         "with the 'subscription' attribute set to a value of \"from\". (Here we assume that the contact does not " +
  268.         "already have a subscription to the user; if that were the case, the 'subscription' attribute would be set " +
  269.         "to a value of \"both\", as explained under Appendix A.)")
  270.     public void testPresenceApprovalYieldsRosterPush2() throws Exception {
  271.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

  272.         // Setup fixture: establish one-way subscription.
  273.         rosterOne.setSubscriptionMode(Roster.SubscriptionMode.accept_all);

  274.         final SimpleResultSyncPoint fixtureComplete = new SimpleResultSyncPoint();
  275.         RosterListener rosterListenerTwo = new AbstractRosterListener() {
  276.             @Override
  277.             public void entriesAdded(Collection<Jid> addresses) {
  278.                 checkIfAdded(addresses);
  279.             }
  280.             @Override
  281.             public void entriesUpdated(Collection<Jid> addresses) {
  282.                 checkIfAdded(addresses);
  283.             }
  284.             private void checkIfAdded(Collection<Jid> addresses) {
  285.                 for (Jid jid : addresses) {
  286.                     final BareJid bareJid = conOne.getUser().asBareJid();
  287.                     if (!jid.equals(bareJid)) {
  288.                         continue;
  289.                     }
  290.                     if (rosterTwo.getEntry(bareJid) == null) {
  291.                         continue;
  292.                     }
  293.                     if (rosterTwo.getEntry(bareJid).getType() == ItemType.none) {
  294.                         continue;
  295.                     }
  296.                     fixtureComplete.signal();
  297.                     rosterTwo.removeRosterListener(this);
  298.                 }
  299.             }
  300.         };
  301.         rosterTwo.addRosterListener(rosterListenerTwo);

  302.         final Presence subscribeOne = conTwo.getStanzaFactory().buildPresenceStanza()
  303.                 .ofType(Presence.Type.subscribe)
  304.                 .to(conOne.getUser().asBareJid())
  305.                 .build();
  306.         try {
  307.             conTwo.sendStanza(subscribeOne);

  308.             fixtureComplete.waitForResult(connection.getReplyTimeout());
  309.         } finally {
  310.             rosterOne.setSubscriptionMode(Roster.getDefaultSubscriptionMode());
  311.             rosterTwo.removeRosterListener(rosterListenerTwo);
  312.         }

  313.         // Setup fixture is now complete. Execute the test.
  314.         rosterTwo.setSubscriptionMode(Roster.SubscriptionMode.accept_all);

  315.         final ResultSyncPoint<RosterEntry, Exception> updated = new ResultSyncPoint<>();

  316.         rosterListenerTwo = new AbstractRosterListener() {
  317.             @Override
  318.             public void entriesUpdated(Collection<Jid> addresses) {
  319.                 for (Jid jid : addresses) {
  320.                     if (!jid.equals(conOne.getUser().asBareJid())) {
  321.                         continue;
  322.                     }
  323.                     BareJid bareJid = conOne.getUser().asBareJid();
  324.                     updated.signal(rosterTwo.getEntry(bareJid));
  325.                 }
  326.             }
  327.         };
  328.         rosterTwo.addRosterListener(rosterListenerTwo);

  329.         final Presence subscribeTwo = conOne.getStanzaFactory().buildPresenceStanza()
  330.                 .ofType(Presence.Type.subscribe)
  331.                 .to(conTwo.getUser().asBareJid())
  332.                 .build();

  333.         try {
  334.             conOne.sendStanza(subscribeTwo);

  335.             final RosterEntry entry = assertResult(updated, "Expected '" + conTwo.getUser() + "' to receive a roster push with an update for the entry of '" + conOne.getUser().asBareJid() + "' after '" + conOne.getUser() + "' approved their subscription request.");
  336.             assertEquals(ItemType.both, entry.getType(), "Unexpected type for '" + conOne.getUser().asBareJid() + "''s entry in '" + conTwo.getUser().asBareJid() + "''s roster.");
  337.         } finally {
  338.             rosterTwo.setSubscriptionMode(Roster.getDefaultSubscriptionMode());
  339.             rosterTwo.removeRosterListener(rosterListenerTwo);
  340.         }
  341.     }

  342.     /**
  343.      * Asserts that when a presence subscription request is approved, the server sends the latest presence of the now
  344.      * subscribed entity to the subscriber.
  345.      *
  346.      * @throws Exception when errors occur
  347.      */
  348.     @SmackIntegrationTest(section = "3.1.5", quote =
  349.         "The contact's server MUST then also send current presence to the user from each of the contact's available resources.")
  350.     public void testCurrentPresenceSentAfterSubscriptionApproval() throws Exception {
  351.         IntegrationTestRosterUtil.ensureBothAccountsAreNotInEachOthersRoster(conOne, conTwo);

  352.         final String needle = "Look for me!";
  353.         conTwo.sendStanza(conTwo.getStanzaFactory().buildPresenceStanza().setStatus(needle).build());

  354.         rosterTwo.setSubscriptionMode(Roster.SubscriptionMode.accept_all);

  355.         final SimpleResultSyncPoint received = new SimpleResultSyncPoint();
  356.         final StanzaListener stanzaListener = stanza -> {
  357.             final Presence presence = (Presence) stanza;

  358.             String status = presence.getStatus();
  359.             if (status == null) return;

  360.             if (status.equals(needle)) {
  361.                 received.signal();
  362.             }
  363.         };
  364.         conOne.addAsyncStanzaListener(stanzaListener, new AndFilter(StanzaTypeFilter.PRESENCE, FromMatchesFilter.createBare(conTwo.getUser())));

  365.         final Presence subscribe = conOne.getStanzaFactory().buildPresenceStanza()
  366.                 .ofType(Presence.Type.subscribe)
  367.                 .to(conTwo.getUser().asBareJid())
  368.                 .build();

  369.         try {
  370.             conOne.sendStanza(subscribe);

  371.             assertResult(received, "Expected '" + conTwo.getUser() + "' to receive '" + conOne.getUser() + "''s current presence update (including the status '" + needle + "'), but it did not.");
  372.         } finally {
  373.             rosterTwo.setSubscriptionMode(Roster.getDefaultSubscriptionMode());
  374.             conOne.removeAsyncStanzaListener(stanzaListener);
  375.         }
  376.     }

  377. }