authtest

package
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package authtest provides conformance suites for auth.UserDriver and auth.Authenticator implementations, modeled on testing/fstest.

Run checks auth.Authenticator implementations against the rules every authenticator shares. Call it from the authenticator's tests with factories for a request without credentials, one with valid credentials and, through WithInvalid, one with rejected credentials. Option is one type that serves both suites.

RunUserDriver seeds a driver with known User fixtures and runs one subtest per documented behavior: a found user with its version and claims, a missing user, a disabled user and invalid subjects. Fixture subjects are decimal digits, so drivers keyed by integers, strings or text types can all pass.

Example:

func TestDriver(t *testing.T) {
	authtest.RunUserDriver(t, func(t *testing.T, users []authtest.User) auth.UserDriver {
		driver := memoryauth.New()
		// Seed driver from users.
		return driver
	})
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run added in v0.3.0

func Run(t *testing.T, authenticate auth.Authenticator, newAnonymous, newValid func(t *testing.T) *http.Request, opts ...Option)

Run checks that authenticate follows the auth.Authenticator contract: a request without credentials yields auth.ErrNoCredentials and passes auth.Middleware anonymously, a request with valid credentials yields an identity that the middleware stores in the context, and, with WithInvalid, rejected credentials yield auth.ErrUnauthenticated and stop the request.

newAnonymous and newValid are called once per subtest; each request must carry whatever context the authenticator reads, such as a session.

Example:

func TestBearer(t *testing.T) {
	authenticate := auth.Bearer(verify)
	authtest.Run(t, authenticate, anonymousRequest, validRequest,
		authtest.WithInvalid(forgedRequest))
}
Example
package main

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/auth/authtest"
)

func main() {
	authenticate := auth.Bearer(func(_ context.Context, token string) (auth.Identity, error) {
		if token != "good" {
			return auth.Identity{}, errors.New("rejected token")
		}

		return auth.NewIdentity("42"), nil
	})
	request := func(header string) func(t *testing.T) *http.Request {
		return func(*testing.T) *http.Request {
			r := httptest.NewRequest(http.MethodGet, "/", nil)

			if header != "" {
				r.Header.Set("Authorization", header)
			}

			return r
		}
	}

	// In a real package this is a Test function receiving its own *testing.T.
	_ = func(t *testing.T) {
		authtest.Run(t, authenticate, request(""), request("Bearer good"),
			authtest.WithInvalid(request("Bearer forged")))
	}

	fmt.Println("run the suite from a Test function")
}
Output:
run the suite from a Test function

func RunUserDriver

func RunUserDriver(t *testing.T, newDriver func(t *testing.T, users []User) auth.UserDriver, opts ...Option)

RunUserDriver executes the conformance suite against drivers returned by newDriver. newDriver is called once per subtest with the fixtures the driver must contain (one enabled user with a version and claims, one disabled user) and registers any cleanup on t. The suite reports every deviation with t.Errorf or t.Fatalf in a subtest named after the behavior.

Example:

func TestMemoryDriver(t *testing.T) {
	authtest.RunUserDriver(t, func(t *testing.T, users []authtest.User) auth.UserDriver {
		driver := memoryauth.New()
		for _, user := range users {
			_ = driver.Put(auth.UserRecord{Subject: user.Subject, Version: user.Version, Claims: user.Claims})
			if user.Disabled {
				_ = driver.Disable(user.Subject)
			}
		}
		return driver
	})
}
Example
package main

import (
	"fmt"
	"testing"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/auth/authtest"
	"arkoren.dev/core/auth/memoryauth"
)

// seededDriver returns a memory driver containing users.
func seededDriver(users []authtest.User) auth.UserDriver {
	driver := memoryauth.New()

	for _, user := range users {
		_ = driver.Put(auth.UserRecord{Subject: user.Subject, Version: user.Version, Claims: user.Claims})

		if user.Disabled {
			_ = driver.Disable(user.Subject)
		}
	}

	return driver
}

func main() {
	// In a real package this is a Test function receiving its own *testing.T.
	_ = func(t *testing.T) {
		authtest.RunUserDriver(t, func(t *testing.T, users []authtest.User) auth.UserDriver {
			return seededDriver(users)
		})
	}

	fmt.Println("run the suite from a Test function")
}
Output:
run the suite from a Test function

Types

type Option

type Option func(*settings)

Option configures Run or RunUserDriver; create one with WithTimeout, WithInvalid or WithIdentity. A suite ignores the options it does not use: WithTimeout only affects RunUserDriver, the other two only Run.

Example:

option := authtest.WithTimeout(time.Minute)
authtest.RunUserDriver(t, newDriver, option)
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth/authtest"
)

func main() {
	option := authtest.Option(authtest.WithTimeout(1))

	fmt.Println(option != nil)
}
Output:
true

func WithIdentity added in v0.3.0

func WithIdentity(check func(t *testing.T, identity auth.Identity)) Option

WithIdentity supplies a check run on the auth.Identity resolved from the valid request, for example comparing its subject. It only affects Run.

Example:

authtest.Run(t, authenticate, anonymousRequest, validRequest,
	authtest.WithIdentity(func(t *testing.T, identity auth.Identity) {
		if identity.Subject() != "42" {
			t.Fatalf("subject = %q", identity.Subject())
		}
	}))
Example
package main

import (
	"fmt"
	"testing"

	"arkoren.dev/core/auth"
	"arkoren.dev/core/auth/authtest"
)

func main() {
	option := authtest.WithIdentity(func(t *testing.T, identity auth.Identity) {
		if identity.Subject() != "42" {
			t.Fatalf("subject = %q", identity.Subject())
		}
	})

	fmt.Println(option != nil)
}
Output:
true

func WithInvalid added in v0.3.0

func WithInvalid(newRequest func(t *testing.T) *http.Request) Option

WithInvalid supplies a factory for a request carrying credentials the authenticator rejects, such as an expired or forged token. It enables the check that rejected credentials yield auth.ErrUnauthenticated. Leave it out for authenticators without a notion of invalid credentials, such as auth.Guard.Authenticator. It only affects Run.

Example:

authtest.Run(t, authenticate, anonymousRequest, validRequest,
	authtest.WithInvalid(forgedRequest))
Example
package main

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"testing"

	"arkoren.dev/core/auth/authtest"
)

func main() {
	option := authtest.WithInvalid(func(*testing.T) *http.Request {
		return httptest.NewRequest(http.MethodGet, "/", nil)
	})

	fmt.Println(option != nil)
}
Output:
true

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout bounds every subtest's context, for slow remote drivers. A zero or negative timeout keeps the default of 30 seconds.

Example:

authtest.RunUserDriver(t, newDriver, authtest.WithTimeout(time.Minute))
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth/authtest"
)

func main() {
	option := authtest.WithTimeout(0) // Zero keeps the 30 second default.

	fmt.Println(option != nil)
}
Output:
true

type User

type User struct {
	// Subject identifies the user. Fixture subjects are decimal digits.
	Subject string

	// Version must come back as [auth.UserRecord.Version].
	Version string

	// Claims must come back as [auth.UserRecord.Claims].
	Claims map[string]any

	// Disabled users must make Find return [auth.ErrUserDisabled].
	Disabled bool
}

User is a fixture the suite asks a driver under test to contain.

Example:

authtest.User{Subject: "1", Version: "v1", Claims: map[string]any{"role": "admin"}}
Example
package main

import (
	"fmt"

	"arkoren.dev/core/auth/authtest"
)

func main() {
	user := authtest.User{Subject: "1", Version: "v7", Claims: map[string]any{"role": "admin"}}

	fmt.Println(user.Subject, user.Version, user.Disabled)
}
Output:
1 v7 false

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL