text:
<?php

namespace Opulence\Authentication\Tests\Credentials\Authenticators;

use InvalidArgumentException;
use Opulence\Authentication\Credentials\Authenticators\Authenticator;
use Opulence\Authentication\Credentials\Authenticators\IAuthenticator;
use Opulence\Authentication\Credentials\Authenticators\IAuthenticatorRegistry;
use Opulence\Authentication\Credentials\ICredential;

/**
 * Tests the authenticator
 */
class AuthenticatorTest extends \PHPUnit\Framework\TestCase
{
    /** @var Authenticator The authenticator to use in tests */
    private $authenticator = null;
    /** @var IAuthenticatorRegistry|\PHPUnit_Framework_MockObject_MockObject The authenticator registry to use in tests */
    private $authenticatorRegistry = null;

    /**
     * Sets up the tests
     */
    public function setUp() : void
    {
        $this->authenticatorRegistry = $this->createMock(IAuthenticatorRegistry::class);
        $this->authenticator = new Authenticator($this->authenticatorRegistry);
    }

    /**
     * Tests an authenticator that successfully authenticates a credential
     */
    public function testAuthenticatorThatSuccessfullyAuthenticatesCredential()
    {
        /** @var ICredential|\PHPUnit_Framework_MockObject_MockObject $credential */
        $credential = $this->createMock(ICredential::class);
        $credential->expects($this->once())
            ->method('getType')
            ->willReturn('foo');
        $subject = null;
        $actualAuthenticator = $this->createMock(IAuthenticator::class);
        $actualAuthenticator->expects($this->once())
            ->method('authenticate')
            ->with($credential, $subject)
            ->willReturn(true);
        $this->authenticatorRegistry->expects($this->once())
            ->method('getAuthenticators')
            ->with('foo')
            ->willReturn([$actualAuthenticator]);
        $this->assertTrue($this->authenticator->authenticate($credential, $subject));
    }

    /**
     * Tests an authenticator that unsuccessfully authenticates a credential
     */
    public function testAuthenticatorThatUnsuccessfullyAuthenticatesCredential()
    {
        /** @var ICredential|\PHPUnit_Framework_MockObject_MockObject $credential */
        $credential = $this->createMock(ICredential::class);
        $credential->expects($this->once())
            ->method('getType')
            ->willReturn('foo');
        $subject = null;
        $actualAuthenticator = $this->createMock(IAuthenticator::class);
        $actualAuthenticator->expects($this->once())
            ->method('authenticate')
            ->with($credential, $subject)
            ->willReturn(false);
        $this->authenticatorRegistry->expects($this->once())
            ->method('getAuthenticators')
            ->with('foo')
            ->willReturn([$actualAuthenticator]);
        $this->assertFalse($this->authenticator->authenticate($credential, $subject));
    }

    /**
     * Tests that an exception is thrown with no authenticator for a credential
     */
    public function testExceptionThrownWithNoAuthenticatorForCredential()
    {
        $this->expectException(InvalidArgumentException::class);
        /** @var ICredential|\PHPUnit_Framework_MockObject_MockObject $credential */
        $credential = $this->createMock(ICredential::class);
        $credential->expects($this->once())
            ->method('getType')
            ->willReturn('foo');
        $subject = null;
        $this->authenticatorRegistry->expects($this->once())
            ->method('getAuthenticators')
            ->with('foo')
            ->willThrowException(new InvalidArgumentException);
        $this->authenticator->authenticate($credential, $subject);
    }
}

redpajama_set_name: RedPajamaGithub


text:
namespace Trinity {
        // Currently, we don't really need to query for total matches in the current document
        // but if we do, or you need it in your handler for whatever reason, uncomment RDP_NEED_TOTAL_MATCHES
        // and rebuild. This is not enabled because inflating the vtables is not worth it for a call that
        // you may not use.
        //
        // This, along with moving score() out of relevant_document_provider is done so that we
        // reduce the vtable size of Iterator and thereby reduce cache-misses.
        //
        // We could probably move Iterator::curDocument into relevant_document_provider thereby not having
        // to make document() virtual, though I am not sure how we'd go about making IteratorScorer subclasses of
        // relevant_document_provider do the right thing.
        //#define RDP_NEED_TOTAL_MATCHES 1
        struct relevant_document_provider {
                virtual isrc_docid_t document() const noexcept = 0;

#ifdef RDP_NEED_TOTAL_MATCHES
                virtual uint32_t total_matches() = 0;
#endif

                // In the past, relevant_document_provider() had a virtual double score() decl.
                // but that meant we 'd inflate the vtable of Iterators, which are also relevant_document_provider
                // for no reason -- they do not provide scores.
                //
                // Instead, considering that if you invoke score() it must be because the relevant_document_provider you are
                // invoking it on is an IteratorScorer(), we just do what score() impl. does and thereby
                // no longer need to make score() virtual.
                //
                // The only downside is that relevant_document is somewhat ugly now . It contains a dummy iterator which is
                // used just for setting the current document. It's a fair tradeoff though, and consdidering we only
                // make use of it for ExecFlags::DocumentsOnly, it's OK.
                inline double score();
        };

        namespace DocsSetIterators {
                struct Iterator;
        }

        // This simply wraps an iterator, and also provides a score for it when asked.
        struct IteratorScorer
            : public relevant_document_provider {
                DocsSetIterators::Iterator *const it;

                IteratorScorer(DocsSetIterators::Iterator *const it_)
                    : it{it_} {
                }

                virtual ~IteratorScorer() {
                }

#ifdef RDP_NEED_TOTAL_MATCHES
                inline uint32_t total_matches() override final;
#endif

                inline isrc_docid_t document() const noexcept override final;

                // Will return the wrapped iterator, except for e.g Filter and Optional
                // where we only really want to advance the required or main respectively iterator
                // For now, this is not supported, but it may be in the future as an optimization.
                // TODO: consider this
                inline virtual DocsSetIterators::Iterator *iterator() {
                        return it;
                }

                virtual double iterator_score() = 0;
        };

        double relevant_document_provider::score() {
                // If you tried to get a score, then this is a IteratorScorer
                // we used to virtual double score() = 0 here
                // but we really don't want to inflate Iterator's vtable with it
                return static_cast<IteratorScorer *>(this)->iterator_score();
        }
} // namespace Trinity

#ifdef __clang__
#pragma GCC diagnostic pop
#endif


text:
package mssql

import (
	"database/sql"
	"fmt"
	"strings"
	"sync"

	_ "github.com/denisenkom/go-mssqldb"
	"github.com/hashicorp/vault/logical"
	"github.com/hashicorp/vault/logical/framework"
)

func Factory(conf *logical.BackendConfig) (logical.Backend, error) {
	return Backend().Setup(conf)
}

func Backend() *backend {
	var b backend
	b.Backend = &framework.Backend{
		Help: strings.TrimSpace(backendHelp),

		Paths: []*framework.Path{
			pathConfigConnection(&b),
			pathConfigLease(&b),
			pathListRoles(&b),
			pathRoles(&b),
			pathCredsCreate(&b),
		},

		Secrets: []*framework.Secret{
			secretCreds(&b),
		},
	}

	return &b
}

type backend struct {
	*framework.Backend

	db        *sql.DB
	defaultDb string
	lock      sync.Mutex
}

// DB returns the default database connection.
func (b *backend) DB(s logical.Storage) (*sql.DB, error) {
	b.lock.Lock()
	defer b.lock.Unlock()

	// If we already have a DB, we got it!
	if b.db != nil {
		if err := b.db.Ping(); err == nil {
			return b.db, nil
		}
		// If the ping was unsuccessful, close it and ignore errors as we'll be
		// reestablishing anyways
		b.db.Close()
	}

	// Otherwise, attempt to make connection
	entry, err := s.Get("config/connection")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil, fmt.Errorf("configure the DB connection with config/connection first")
	}

	var connConfig connectionConfig
	if err := entry.DecodeJSON(&connConfig); err != nil {
		return nil, err
	}
	connString := connConfig.ConnectionString

	db, err := sql.Open("mssql", connString)
	if err != nil {
		return nil, err
	}

	// Set some connection pool settings. We don't need much of this,
	// since the request rate shouldn't be high.
	db.SetMaxOpenConns(connConfig.MaxOpenConnections)

	stmt, err := db.Prepare("SELECT db_name();")
	if err != nil {
		return nil, err
	}
	defer stmt.Close()

	err = stmt.QueryRow().Scan(&b.defaultDb)
	if err != nil {
		return nil, err
	}

	b.db = db
	return b.db, nil
}

// ResetDB forces a connection next time DB() is called.
func (b *backend) ResetDB() {
	b.lock.Lock()
	defer b.lock.Unlock()

	if b.db != nil {
		b.db.Close()
	}

	b.db = nil
}

// LeaseConfig returns the lease configuration
func (b *backend) LeaseConfig(s logical.Storage) (*configLease, error) {
	entry, err := s.Get("config/lease")
	if err != nil {
		return nil, err
	}
	if entry == nil {
		return nil, nil
	}

	var result configLease
	if err := entry.DecodeJSON(&result); err != nil {
		return nil, err
	}

	return &result, nil
}

const backendHelp = `
The MSSQL backend dynamically generates database users.

After mounting this backend, configure it using the endpoints within
the "config/" path.

This backend does not support Azure SQL Databases.
`