<commit_before>package xmpp

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net"
	"testing"
	"time"
)

const (
	// Default port is not standard XMPP port to avoid interfering
	// with local running XMPP server
	testXMPPAddress = "localhost:15222"

	defaultTimeout = 2 * time.Second
)

func TestClient_Connect(t *testing.T) {
	// Setup Mock server
	mock := ServerMock{}
	mock.Start(t, testXMPPAddress, handlerConnectSuccess)

	// Test / Check result
	options := Options{Address: testXMPPAddress, Jid: "test@localhost", Password: "<PASSWORD>", Insecure: true}

	var client *Client
	var err error
	if client, err = NewClient(options); err != nil {
		t.Errorf("connect create XMPP client: %s", err)
	}

	if _, err = client.Connect(); err != nil {
		t.Errorf("XMPP connection failed: %s", err)
	}

	mock.Stop()
}

func TestClient_NoInsecure(t *testing.T) {
	// Setup Mock server
	mock := ServerMock{}
	mock.Start(t, testXMPPAddress, handlerAbortTLS)

	// Test / Check result
	options := Options{Address: testXMPPAddress, Jid: "test@localhost", Password: "<PASSWORD>"}

	var client *Client
	var err error
	if client, err = NewClient(options); err != nil {
		t.Errorf("cannot create XMPP client: %s", err)
	}

	if _, err = client.Connect(); err == nil {
		// When insecure is not allowed:
		t.Errorf("should fail as insecure connection is not allowed and server does not support TLS")
	}

	mock.Stop()
}

//=============================================================================
// Basic XMPP Server Mock Handlers.

const serverStreamOpen = "<?xml version='1.0'?><stream:stream to='%s' id='%s' xmlns='%s' xmlns:stream='%s' version='1.0'>"

func handlerConnectSuccess(t *testing.T, c net.Conn) {
	decoder := xml.NewDecoder(c)
	checkOpenStream(t, c, decoder)

	sendStreamFeatures(t, c, decoder) // Send initial features
	readAuth(t, decoder)
	fmt.Fprintln(c, "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"/>")

	checkOpenStream(t, c, decoder) // Reset stream
	sendBindFeature(t, c, decoder) // Send post auth features
	bind(t, c, decoder)
}

// We expect client will abort on TLS
func handlerAbortTLS(t *testing.T, c net.Conn) {
	decoder := xml.NewDecoder(c)

	checkOpenStream(t, c, decoder)

	sendStreamFeatures(t, c, decoder) // Send initial features
	readAuth(t, decoder)
}

func checkOpenStream(t *testing.T, c net.Conn, decoder *xml.Decoder) {
	c.SetDeadline(time.Now().Add(defaultTimeout))
	defer c.SetDeadline(time.Time{})

	for { // TODO clean up. That for loop is not elegant and I prefer bounded recursion.
		var token xml.Token
		token, err := decoder.Token()
		if err != nil {
			t.Errorf("cannot read next token: %s", err)
		}

		switch elem := token.(type) {
		// Wait for first startElement
		case xml.StartElement:
			if elem.Name.Space != NSStream || elem.Name.Local != "stream" {
				err = errors.New("xmpp: expected <stream> but got <" + elem.Name.Local + "> in " + elem.Name.Space)
				return
			}
			if _, err := fmt.Fprintf(c, serverStreamOpen, "localhost", "streamid1", NSClient, NSStream); err != nil {
				t.Errorf("cannot write server stream open: %s", err)
			}
			return
		}
	}
}<commit_msg>Do not expect authentication when client forbid insecure auth<commit_after>package xmpp

import (
	"encoding/xml"
	"errors"
	"fmt"
	"net"
	"testing"
	"time"
)

const (
	// Default port is not standard XMPP port to avoid interfering
	// with local running XMPP server
	testXMPPAddress = "localhost:15222"

	defaultTimeout = 2 * time.Second
)

func TestClient_Connect(t *testing.T) {
	// Setup Mock server
	mock := ServerMock{}
	mock.Start(t, testXMPPAddress, handlerConnectSuccess)

	// Test / Check result
	options := Options{Address: testXMPPAddress, Jid: "test@localhost", Password: "<PASSWORD>", Insecure: true}

	var client *Client
	var err error
	if client, err = NewClient(options); err != nil {
		t.Errorf("connect create XMPP client: %s", err)
	}

	if _, err = client.Connect(); err != nil {
		t.Errorf("XMPP connection failed: %s", err)
	}

	mock.Stop()
}

func TestClient_NoInsecure(t *testing.T) {
	// Setup Mock server
	mock := ServerMock{}
	mock.Start(t, testXMPPAddress, handlerAbortTLS)

	// Test / Check result
	options := Options{Address: testXMPPAddress, Jid: "test@localhost", Password: "<PASSWORD>"}

	var client *Client
	var err error
	if client, err = NewClient(options); err != nil {
		t.Errorf("cannot create XMPP client: %s", err)
	}

	if _, err = client.Connect(); err == nil {
		// When insecure is not allowed:
		t.Errorf("should fail as insecure connection is not allowed and server does not support TLS")
	}

	mock.Stop()
}

//=============================================================================
// Basic XMPP Server Mock Handlers.

const serverStreamOpen = "<?xml version='1.0'?><stream:stream to='%s' id='%s' xmlns='%s' xmlns:stream='%s' version='1.0'>"

func handlerConnectSuccess(t *testing.T, c net.Conn) {
	decoder := xml.NewDecoder(c)
	checkOpenStream(t, c, decoder)

	sendStreamFeatures(t, c, decoder) // Send initial features
	readAuth(t, decoder)
	fmt.Fprintln(c, "<success xmlns=\"urn:ietf:params:xml:ns:xmpp-sasl\"/>")

	checkOpenStream(t, c, decoder) // Reset stream
	sendBindFeature(t, c, decoder) // Send post auth features
	bind(t, c, decoder)
}

// We expect client will abort on TLS
func handlerAbortTLS(t *testing.T, c net.Conn) {
	decoder := xml.NewDecoder(c)
	checkOpenStream(t, c, decoder)
	sendStreamFeatures(t, c, decoder) // Send initial features
}

func checkOpenStream(t *testing.T, c net.Conn, decoder *xml.Decoder) {
	c.SetDeadline(time.Now().Add(defaultTimeout))
	defer c.SetDeadline(time.Time{})

	for { // TODO clean up. That for loop is not elegant and I prefer bounded recursion.
		var token xml.Token
		token, err := decoder.Token()
		if err != nil {
			t.Errorf("cannot read next token: %s", err)
		}

		switch elem := token.(type) {
		// Wait for first startElement
		case xml.StartElement:
			if elem.Name.Space != NSStream || elem.Name.Local != "stream" {
				err = errors.New("xmpp: expected <stream> but got <" + elem.Name.Local + "> in " + elem.Name.Space)
				return
			}
			if _, err := fmt.Fprintf(c, serverStreamOpen, "localhost", "streamid1", NSClient, NSStream); err != nil {
				t.Errorf("cannot write server stream open: %s", err)
			}
			return
		}
	}
}
{'fraction_non_alphanumeric': 0.16368572341105078, 'fraction_numerical': 0.0035132545512615776, 'mean_word_length': 4.150493421052632, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 2, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 22}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5132160', 'n_tokens_mistral': 2241, 'n_tokens_neox': 2066, 'n_words': 612}