auth

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Mar 25, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// AuthSchemeL402 is the L402 (macaroon + preimage) authentication
	// scheme identifier.
	AuthSchemeL402 = "l402"

	// AuthSchemeMPP is the Payment HTTP Authentication Scheme identifier.
	AuthSchemeMPP = "mpp"

	// AuthSchemeL402MPP enables both L402 and MPP simultaneously.
	AuthSchemeL402MPP = "l402+mpp"
)
View Source
const (
	// DefaultInvoiceLookupTimeout is the default maximum time we wait for
	// an invoice update to arrive.
	DefaultInvoiceLookupTimeout = 3 * time.Second
)
View Source
const Subsystem = "AUTH"

Variables

This section is empty.

Functions

func DisableLog

func DisableLog()

DisableLog disables all library log output. Logging output is disabled by default until UseLogger is called.

func UseLogger

func UseLogger(logger btclog.Logger)

UseLogger uses a specified Logger to output package logging info. This should be used in preference to SetLogWriter if the caller is also using btclog.

Types

type Authenticator

type Authenticator interface {
	// Accept returns whether or not the header successfully authenticates
	// the user to a given backend service.
	Accept(*http.Header, string) bool

	// FreshChallengeHeader returns a header containing a challenge for the
	// user to complete.
	FreshChallengeHeader(string, int64) (http.Header, error)
}

Authenticator is the generic interface for validating client headers and returning new challenge headers.

type InvoiceChecker

type InvoiceChecker interface {
	// VerifyInvoiceStatus checks that an invoice identified by a payment
	// hash has the desired status. To make sure we don't fail while the
	// invoice update is still on its way, we try several times until either
	// the desired status is set or the given timeout is reached.
	VerifyInvoiceStatus(lntypes.Hash, lnrpc.Invoice_InvoiceState,
		time.Duration) error
}

InvoiceChecker is an entity that is able to check the status of an invoice, particularly whether it's been paid or not.

type L402Authenticator

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

L402Authenticator is an authenticator that uses the L402 protocol to authenticate requests.

func NewL402Authenticator

func NewL402Authenticator(minter Minter,
	checker InvoiceChecker) *L402Authenticator

NewL402Authenticator creates a new authenticator that authenticates requests based on L402 tokens.

func (*L402Authenticator) Accept

func (l *L402Authenticator) Accept(header *http.Header, serviceName string) bool

Accept returns whether or not the header successfully authenticates the user to a given backend service.

NOTE: This is part of the Authenticator interface.

func (*L402Authenticator) FreshChallengeHeader

func (l *L402Authenticator) FreshChallengeHeader(serviceName string,
	servicePrice int64) (http.Header, error)

FreshChallengeHeader returns a header containing a challenge for the user to complete.

NOTE: This is part of the Authenticator interface.

func (*L402Authenticator) Scheme added in v0.5.0

func (l *L402Authenticator) Scheme() string

Scheme returns the authentication scheme identifier for the L402 authenticator.

NOTE: This implements the SchemeTagged interface.

type Level

type Level string
const (
	// LevelOff is the default level where no authentication is required.
	LevelOff Level = "off"
)

func (Level) FreebieCount

func (l Level) FreebieCount() freebie.Count

func (Level) IsFreebie

func (l Level) IsFreebie() bool

func (Level) IsOff

func (l Level) IsOff() bool

func (Level) IsOn

func (l Level) IsOn() bool

type MPPAuthenticator added in v0.5.0

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

MPPAuthenticator is an authenticator that implements the Payment HTTP Authentication Scheme for the Lightning "charge" intent. It issues BOLT11 invoices as challenges and verifies payment preimages as credentials.

func NewMPPAuthenticator added in v0.5.0

func NewMPPAuthenticator(challenger mint.Challenger, checker InvoiceChecker,
	realm string, hmacSecret []byte, network string,
	txnRecorder TransactionRecorder) *MPPAuthenticator

func (*MPPAuthenticator) Accept added in v0.5.0

func (a *MPPAuthenticator) Accept(header *http.Header,
	serviceName string) bool

Accept returns whether the header contains a valid Payment credential for the Lightning charge intent.

NOTE: This is part of the Authenticator interface.

func (*MPPAuthenticator) FreshChallengeHeader added in v0.5.0

func (a *MPPAuthenticator) FreshChallengeHeader(serviceName string,
	servicePrice int64) (http.Header, error)

FreshChallengeHeader returns a WWW-Authenticate: Payment header containing a charge challenge with a fresh BOLT11 invoice.

NOTE: This is part of the Authenticator interface.

func (*MPPAuthenticator) ReceiptHeader added in v0.5.0

func (a *MPPAuthenticator) ReceiptHeader(header *http.Header,
	serviceName string) http.Header

ReceiptHeader returns a Payment-Receipt header for a successfully authenticated charge request.

NOTE: This is part of the ReceiptProvider interface.

func (*MPPAuthenticator) Scheme added in v0.5.0

func (a *MPPAuthenticator) Scheme() string

Scheme returns the authentication scheme identifier for the MPP charge authenticator.

NOTE: This implements the SchemeTagged interface.

type MPPSessionAuthenticator added in v0.5.0

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

MPPSessionAuthenticator is an authenticator that implements the Payment HTTP Authentication Scheme for the Lightning "session" intent. It manages prepaid sessions with deposit, bearer, top-up, and close operations.

func NewMPPSessionAuthenticator added in v0.5.0

func NewMPPSessionAuthenticator(
	cfg *MPPSessionConfig) *MPPSessionAuthenticator

NewMPPSessionAuthenticator creates a new session intent authenticator.

func (*MPPSessionAuthenticator) Accept added in v0.5.0

func (a *MPPSessionAuthenticator) Accept(header *http.Header,
	serviceName string) bool

Accept returns whether the header contains a valid Payment credential for the Lightning session intent.

NOTE: This is part of the Authenticator interface.

func (*MPPSessionAuthenticator) FreshChallengeHeader added in v0.5.0

func (a *MPPSessionAuthenticator) FreshChallengeHeader(serviceName string,
	servicePrice int64) (http.Header, error)

FreshChallengeHeader returns a WWW-Authenticate: Payment header containing a session challenge with a fresh deposit invoice.

NOTE: This is part of the Authenticator interface.

func (*MPPSessionAuthenticator) ReceiptHeader added in v0.5.0

func (a *MPPSessionAuthenticator) ReceiptHeader(header *http.Header,
	serviceName string) http.Header

ReceiptHeader returns a Payment-Receipt header for a successfully authenticated session request.

NOTE: This is part of the ReceiptProvider interface.

func (*MPPSessionAuthenticator) Scheme added in v0.5.0

func (a *MPPSessionAuthenticator) Scheme() string

Scheme returns the authentication scheme identifier for the MPP session authenticator.

NOTE: This implements the SchemeTagged interface.

type MPPSessionConfig added in v0.5.0

type MPPSessionConfig struct {
	Challenger        mint.Challenger
	Checker           InvoiceChecker
	SessionStore      SessionStore
	PaymentSender     PaymentSender
	Realm             string
	HMACSecret        []byte
	Network           string
	DepositMultiplier int
	IdleTimeout       time.Duration
}

MPPSessionConfig holds the configuration for the session authenticator.

type Minter

type Minter interface {
	// MintL402 mints a new L402 for the target services.
	MintL402(context.Context, ...l402.Service) (*macaroon.Macaroon, string, error)

	// VerifyL402 attempts to verify an L402 with the given parameters.
	VerifyL402(context.Context, *mint.VerificationParams) error
}

Minter is an entity that is able to mint and verify L402s for a set of services.

type MockAuthenticator

type MockAuthenticator struct{}

MockAuthenticator is a mock implementation of the authenticator.

func NewMockAuthenticator

func NewMockAuthenticator() *MockAuthenticator

NewMockAuthenticator returns a new MockAuthenticator instance.

func (MockAuthenticator) Accept

func (a MockAuthenticator) Accept(header *http.Header, _ string) bool

Accept returns whether or not the header successfully authenticates the user to a given backend service.

func (MockAuthenticator) FreshChallengeHeader

func (a MockAuthenticator) FreshChallengeHeader(string, int64) (http.Header,
	error)

FreshChallengeHeader returns a header containing a challenge for the user to complete.

type MultiAuthenticator added in v0.5.0

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

MultiAuthenticator wraps multiple Authenticator implementations and tries each in order. It supports both the Authenticator and ReceiptProvider interfaces, delegating receipt generation to whichever sub-authenticator handles the credential type.

func NewMultiAuthenticator added in v0.5.0

func NewMultiAuthenticator(auths ...Authenticator) *MultiAuthenticator

NewMultiAuthenticator creates a new MultiAuthenticator that tries each authenticator in order.

func (*MultiAuthenticator) Accept added in v0.5.0

func (m *MultiAuthenticator) Accept(header *http.Header,
	serviceName string) bool

Accept returns whether any of the wrapped authenticators accept the request. The first authenticator that returns true wins. This delegates to AcceptForScheme with an empty scheme, which tries all authenticators.

NOTE: This is part of the Authenticator interface.

func (*MultiAuthenticator) AcceptForScheme added in v0.5.0

func (m *MultiAuthenticator) AcceptForScheme(header *http.Header,
	serviceName string, scheme string) bool

AcceptForScheme returns whether any of the wrapped authenticators that match the given auth scheme accept the request. An empty scheme tries all authenticators (backwards compatible). The scheme string can be "l402", "mpp", or "l402+mpp".

func (*MultiAuthenticator) FreshChallengeHeader added in v0.5.0

func (m *MultiAuthenticator) FreshChallengeHeader(serviceName string,
	servicePrice int64) (http.Header, error)

FreshChallengeHeader returns merged challenge headers from all wrapped authenticators. This allows a 402 response to include challenges for multiple authentication schemes (e.g., both L402 and Payment), letting the client choose which scheme to use.

NOTE: This is part of the Authenticator interface.

func (*MultiAuthenticator) ReceiptHeader added in v0.5.0

func (m *MultiAuthenticator) ReceiptHeader(header *http.Header,
	serviceName string) http.Header

ReceiptHeader tries each sub-authenticator that implements ReceiptProvider and returns the first non-nil receipt. This avoids the race condition of storing a per-request index on the shared struct; instead, each provider inspects the credential and only produces a receipt if it handles that credential type.

NOTE: This is part of the ReceiptProvider interface.

type PaymentSender added in v0.5.0

type PaymentSender interface {
	// SendPayment sends a payment to the given invoice with the specified
	// amount in satoshis. Returns the payment preimage hex on success.
	SendPayment(ctx context.Context, invoice string,
		amtSats int64) (string, error)
}

PaymentSender is an interface for sending Lightning payments. This is used by the session authenticator to refund unspent balance when a session is closed.

type ReceiptProvider added in v0.5.0

type ReceiptProvider interface {
	// ReceiptHeader returns any response headers that should be added to
	// the proxied response for a successfully authenticated request. The
	// request headers and service name are provided for context. Returns
	// nil if no receipt headers are needed.
	ReceiptHeader(*http.Header, string) http.Header
}

ReceiptProvider is an optional interface that authenticators can implement to provide response headers (e.g., Payment-Receipt) for successfully authenticated requests. This is used by the MPP authenticator to add Payment-Receipt headers to proxied responses.

type SchemeTagged added in v0.5.0

type SchemeTagged interface {
	// Scheme returns the authentication scheme identifier (e.g., "l402"
	// or "mpp") that this authenticator handles.
	Scheme() string
}

SchemeTagged is an optional interface that authenticators can implement to declare which authentication scheme they handle. This is used by MultiAuthenticator to filter sub-authenticators based on the per-service auth scheme setting.

type Session added in v0.5.0

type Session struct {
	// SessionID is the payment hash of the deposit invoice, encoded as a
	// lowercase hex string. Serves as the unique session identifier.
	SessionID string

	// PaymentHash is the raw 32-byte payment hash of the deposit invoice.
	PaymentHash lntypes.Hash

	// DepositSats is the total satoshis deposited into the session.
	// Increases with each successful top-up.
	DepositSats int64

	// SpentSats is the running total of satoshis charged against the
	// session.
	SpentSats int64

	// ReturnInvoice is the BOLT11 return invoice for refunds on close.
	ReturnInvoice string

	// Status is either "open" or "closed".
	Status string

	// CreatedAt is the time the session was created.
	CreatedAt time.Time

	// UpdatedAt is the time the session was last updated.
	UpdatedAt time.Time
}

Session represents an MPP prepaid session. The session is identified by the payment hash of the deposit invoice.

type SessionStore added in v0.5.0

type SessionStore interface {
	// CreateSession creates a new session with the given initial state.
	CreateSession(ctx context.Context, session *Session) error

	// GetSession returns the session with the given session ID.
	GetSession(ctx context.Context, sessionID string) (*Session, error)

	// UpdateSessionBalance atomically adds the given amount to the
	// session's deposit balance.
	UpdateSessionBalance(ctx context.Context, sessionID string,
		addSats int64) error

	// DeductSessionBalance atomically adds the given amount to the
	// session's spent counter. Returns an error if the deduction would
	// exceed the deposit balance.
	DeductSessionBalance(ctx context.Context, sessionID string,
		amount int64) error

	// CloseSession marks the session as closed. No further operations are
	// accepted on a closed session.
	CloseSession(ctx context.Context, sessionID string) error

	// CloseSessionAndGetBalance atomically closes the session and returns
	// the remaining balance (deposit_sats - spent_sats). This prevents
	// the TOCTOU race where a concurrent bearer request could deduct
	// balance between a separate read and close.
	CloseSessionAndGetBalance(ctx context.Context,
		sessionID string) (int64, error)
}

SessionStore persists MPP session state for the session intent. Sessions track prepaid balances that are decremented as services are consumed.

type TransactionRecorder added in v0.5.0

type TransactionRecorder interface {
	// RecordMPPTransaction records a pending MPP charge or session
	// payment. The authType distinguishes between "mpp_charge" and
	// "mpp_session".
	RecordMPPTransaction(ctx context.Context, paymentHash []byte,
		serviceName string, priceSats int64,
		authType string) error
}

TransactionRecorder records payment transactions for admin dashboard tracking. Both L402 and MPP payments use this to populate the transactions table.

Jump to

Keyboard shortcuts

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