fakeauth

package
v0.3.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Oct 6, 2025 License: MIT Imports: 10 Imported by: 0

README

Fake Auth Plugin

The Fake Auth Plugin provides a simple way to create authenticated identities during testing without the need for real credentials or external dependencies.

Features

  • Create arbitrary identities for testing
  • Customize default identity values
  • Add validation logic to restrict test identities
  • Simple API for test code to obtain authentication tokens
  • Works with existing auth plugin infrastructure

Usage

Basic Setup
// Create a server with auth and fake auth plugins
s := prefab.New(
    prefab.WithPlugin(auth.Plugin()),
    prefab.WithPlugin(fake.Plugin()),
)
Customizing the Plugin
// Customize the fake auth plugin
s := prefab.New(
    prefab.WithPlugin(auth.Plugin()),
    prefab.WithPlugin(fake.Plugin(
        // Set a custom default identity
        fake.WithDefaultIdentity(auth.Identity{
            Provider:      fake.ProviderName,
            Subject:       "test-admin-123",
            Email:         "admin@example.com",
            Name:          "Test Admin",
            EmailVerified: true,
        }),
        // Add validation logic
        fake.WithIdentityValidator(func(ctx context.Context, creds map[string]string) error {
            // Example: only allow certain test emails
            if email, ok := creds["email"]; ok && email != "" {
                if !strings.HasSuffix(email, "@example.com") {
                    return fmt.Errorf("only @example.com emails allowed in tests")
                }
            }
            return nil
        }),
    )),
)
Using in Integration Tests

The plugin provides type-safe helper functions to create authenticated test clients:

func TestUserAPI(t *testing.T) {
    // Set up the test server with fake auth
    s := setupServer()

    // Create a test client for auth service
    ctx := context.Background()
    authClient := auth.NewAuthServiceClient(s.ClientConn())

    emailVerified := true
    token := fake.MustLogin(ctx, authClient, fake.FakeOptions{
        ID:            "test-user-123",
        Email:         "test@example.com",
        Name:          "Test User",
        EmailVerified: &emailVerified,
    })

    // Use the token for authenticated requests
    md := metadata.Pairs("authorization", token)
    authCtx := metadata.NewOutgoingContext(ctx, md)

    // Make authenticated API calls
    userClient := userapi.NewUserServiceClient(s.ClientConn())
    resp, err := userClient.GetUser(authCtx, &userapi.GetUserRequest{...})
    // ...
}
Login Request Credentials

The fake auth plugin supports the following credentials in the login request:

Key Description Default
id Unique user ID "fake-user-123"
subject Deprecated: Use id instead -
email User email address "fake-user@example.com"
name User display name "Fake User"
email_verified Whether email is verified (true/false) true
error_code Simulate error with this code (int) -
error_message Custom error message for simulated errors "simulated error"

Security Considerations

This plugin is intended for testing only and should never be used in production environments. To prevent accidental use in production:

  1. Only include this plugin in test builds
  2. Use build tags to conditionally include the plugin
  3. Add validation that restricts allowed identities in testing

Example of conditional inclusion:

// +build test

package main

import (
    "github.com/dpup/prefab/plugins/auth/fake"
)

func setupTestServer() {
    // Include fake auth plugin for tests
}

Documentation

Overview

Package fake provides an authentication plugin for testing purposes.

This plugin allows server integrations tests to easily authenticate as any identity without requiring actual authentication credentials or external dependencies.

Index

Constants

View Source
const (
	// PluginName is the name of the fake auth plugin.
	PluginName = "auth_fake"

	// ProviderName is the name of the fake auth provider.
	ProviderName = "fakeauth"
)

Variables

This section is empty.

Functions

func MustLogin

func MustLogin(ctx context.Context, authClient auth.AuthServiceClient, options FakeOptions) string

MustLogin is a convenience function for tests that will panic if login fails. This allows for concise test setup.

Types

type FakeAuthOption

type FakeAuthOption func(*FakeAuthPlugin)

FakeAuthOption allows configuration of the FakeAuthPlugin.

func WithDefaultIdentity

func WithDefaultIdentity(id auth.Identity) FakeAuthOption

WithDefaultIdentity sets the default identity to use when no credentials are provided.

func WithIdentityValidator

func WithIdentityValidator(validator IdentityValidator) FakeAuthOption

WithIdentityValidator allows setting a custom validator for login requests. This can be used to restrict which identities can be created.

type FakeAuthPlugin

type FakeAuthPlugin struct {
	// contains filtered or unexported fields
}

FakeAuthPlugin provides fake authentication for testing purposes. It allows creating arbitrary identities without real credentials.

func Plugin

func Plugin(opts ...FakeAuthOption) *FakeAuthPlugin

Plugin returns a new FakeAuthPlugin for testing purposes.

func (*FakeAuthPlugin) Deps

func (p *FakeAuthPlugin) Deps() []string

From prefab.DependentPlugin.

func (*FakeAuthPlugin) Init

From prefab.InitializablePlugin.

func (*FakeAuthPlugin) Name

func (p *FakeAuthPlugin) Name() string

From prefab.Plugin.

type FakeOptions

type FakeOptions struct {
	// User identity fields
	ID            string // Takes precedence over Subject
	Subject       string // Deprecated: Use ID instead
	Email         string
	Name          string
	EmailVerified *bool

	// Error simulation
	ErrorCode    codes.Code // If set, simulates an error with this code
	ErrorMessage string     // Custom error message (defaults to "simulated error")
}

FakeOptions provides a strongly-typed structure for configuring fake auth login. These options are converted to a credentials map when making login requests.

type IdentityValidator

type IdentityValidator func(ctx context.Context, creds map[string]string) error

IdentityValidator validates fake login credentials. Return an error to reject the login.

Jump to

Keyboard shortcuts

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