authn

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2026 License: Apache-2.0 Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	ProviderOIDC  = "oidc"
	ProviderOAuth = "oauth"
	ProviderLocal = "local"
)
View Source
const ProviderOAuthToken = "oauth_token"

ProviderOAuthToken is the principal method for MCP clients authenticated with an OAuth access token issued by GraphNest's own authorization server. It is deliberately not an interactive method: such principals act as the user but may not mint further credentials.

View Source
const SessionCookieName = "__Host-graphnest_session"

Variables

View Source
var ErrInvalidIdentity = errors.New("invalid identity")
View Source
var ErrInvalidPasswordCredential = errors.New("invalid password credential")
View Source
var ErrOAuthClientQuota = errors.New("oauth client registration limit reached")

ErrOAuthClientQuota reports that the deployment's registration capacity is full.

View Source
var ErrOAuthReplay = errors.New("refresh token replayed")

ErrOAuthReplay reports that a rotated refresh token was presented again outside the grace window. The store revokes the whole grant when this happens.

View Source
var ErrProvisioningUnauthenticated = errors.New("provisioning authentication required")
View Source
var ErrUnauthenticated = errors.New("unauthenticated")

Functions

func IsInteractiveMethod

func IsInteractiveMethod(method string) bool

func IsOAuthAccessToken

func IsOAuthAccessToken(token string) bool

IsOAuthAccessToken reports whether a bearer credential has the shape of an OAuth access token (prefix plus exactly 32 base64url bytes).

func VerifyPassword

func VerifyPassword(password []byte, credential PasswordCredential) bool

func WithFreshPrincipal added in v0.5.0

func WithFreshPrincipal(ctx context.Context, authenticate FreshPrincipalFunc) context.Context

Types

type APITokenMetadata

type APITokenMetadata struct {
	ID             int64
	Prefix         string
	RepositoryIDs  []int64
	DelegationOnly bool
	Delegated      bool
	CreatedAt      time.Time
	LastUsedAt     *time.Time
	ExpiresAt      *time.Time
}

type APITokenRecord

type APITokenRecord struct {
	TokenHash     [32]byte
	Prefix        string
	UserID        int64
	RepositoryIDs []int64
	// DelegationOnly tokens have no ceiling and no repository access; they
	// exist solely to call the delegation endpoint. See Principal.
	DelegationOnly bool
	// Delegated tokens were minted by the delegation endpoint and may not
	// delegate again. See Principal.
	Delegated bool
	CreatedAt time.Time
	ExpiresAt *time.Time
}

type APITokenStore

type APITokenStore interface {
	CreateAPIToken(context.Context, APITokenRecord) (int64, error)
	CreateAPITokenAudited(context.Context, APITokenRecord, audit.Event) (int64, error)
	APIPrincipal(context.Context, [32]byte, time.Time) (Principal, error)
	RevokeAPIToken(context.Context, int64, int64) error
	RevokeAPITokenAudited(context.Context, int64, int64, audit.Event) error
}

type AccessSync

type AccessSync struct{ RepositoryIDs []int64 }

type Authenticator

type Authenticator interface {
	Authenticate(context.Context, string) (Principal, error)
}

type BearerRouter

type BearerRouter struct {
	APITokens Authenticator
	OAuth     Authenticator
}

BearerRouter picks an authenticator by credential shape so each bearer token costs one lookup: OAuth access tokens go to OAuth, everything else to the API-token authenticator.

func (BearerRouter) Authenticate

func (r BearerRouter) Authenticate(ctx context.Context, token string) (Principal, error)

type FreshPrincipalFunc added in v0.5.0

type FreshPrincipalFunc func(context.Context) (Principal, error)

type Identity

type Identity struct {
	Provider, Issuer, Subject, LinkID, DisplayName string
	// Login is the provider's mutable account name; it is only used to name
	// just-in-time provisioned users and is never an identity.
	Login string
	// ProviderToken is the provider's user access token from the login that
	// produced this identity. It is only consulted when a browser login
	// continues an MCP authorization, so the authorization server can re-derive
	// access at refresh time; the session store never persists it.
	ProviderToken string
	// AccessSync, when non-nil, provisions the user on first login and replaces
	// that user's provider-derived repository grants with RepositoryIDs.
	AccessSync *AccessSync
}

type LocalAuthentication

type LocalAuthentication struct {
	UserID        int64
	Token         string
	ExpiresAt     time.Time
	ForceRotation bool
}

type LocalAuthenticator

type LocalAuthenticator struct {
	Store    LocalStore
	Sessions *SessionManager
	Now      func() time.Time
	Dummy    PasswordCredential

	Audit audit.Recorder
	// contains filtered or unexported fields
}

func NewLocalAuthenticator

func NewLocalAuthenticator(store LocalStore, sessions *SessionManager, random io.Reader) (LocalAuthenticator, error)

func (LocalAuthenticator) Authenticate

func (a LocalAuthenticator) Authenticate(ctx context.Context, userName string, password []byte, remoteAddr string) (LocalAuthentication, error)

func (LocalAuthenticator) CompleteLogin

func (a LocalAuthenticator) CompleteLogin(ctx context.Context, verification LocalVerification, prepared PreparedSession) (LocalAuthentication, error)

func (LocalAuthenticator) CompleteRotation

func (a LocalAuthenticator) CompleteRotation(ctx context.Context, verification LocalVerification, prepared PreparedSession) (LocalAuthentication, error)

func (LocalAuthenticator) Verify

func (a LocalAuthenticator) Verify(ctx context.Context, userName string, password []byte, remoteAddr string) (LocalVerification, error)

type LocalStore

type LocalStore interface {
	PasswordCredential(context.Context, string) (int64, PasswordCredential, error)
	ConsumeLoginAttempt(context.Context, [32]byte, time.Time) (bool, time.Time, error)
	ClearLoginFailures(context.Context, [32]byte, [32]byte) error
}

type LocalVerification

type LocalVerification struct {
	UserID        int64
	ForceRotation bool
	Credential    PasswordCredential
	// contains filtered or unexported fields
}

func (LocalVerification) ThrottleKeys

func (verification LocalVerification) ThrottleKeys() ([32]byte, [32]byte)

type LoginFlow

type LoginFlow struct {
	StateHash, BrowserHash                  [32]byte
	Provider, Nonce, CodeVerifier, ReturnTo string
	CreatedAt, ExpiresAt                    time.Time
}

type LoginThrottleError

type LoginThrottleError struct{ RetryAfter time.Duration }

func (*LoginThrottleError) Error

func (e *LoginThrottleError) Error() string

type OAuthAuthorizationRequest

type OAuthAuthorizationRequest struct {
	ID            [32]byte // sha256 of the request handle or authorization code
	Phase         string
	ClientID      string
	UserID        int64 // set when consent is granted
	RedirectURI   string
	CodeChallenge string
	State         string
	Scope         string
	Resource      string
	CreatedAt     time.Time
	ExpiresAt     time.Time
}

OAuthAuthorizationRequest is a pending browser interaction: first awaiting consent (Phase "pending", keyed by the request handle), then awaiting code exchange (Phase "code", keyed by the authorization code).

type OAuthClient

type OAuthClient struct {
	ID           string
	Name         string
	RedirectURIs []string
	CreatedAt    time.Time
	LastUsedAt   time.Time
}

OAuthClient is a dynamically registered public MCP client.

type OAuthGrant

type OAuthGrant struct {
	ID                  int64
	ClientID            string
	UserID              int64
	Scope               string
	AccessHash          [32]byte
	AccessExpiresAt     time.Time
	RefreshHash         [32]byte
	PreviousRefreshHash *[32]byte
	// GitHubTokenCiphertext is the user's GitHub user-to-server token encrypted
	// by the authorization server; the store never sees plaintext.
	GitHubTokenCiphertext []byte
	CreatedAt             time.Time
	LastUsedAt            time.Time
	ExpiresAt             time.Time
	RevokedAt             *time.Time
}

OAuthGrant is one user's authorization of one client. Refresh rotates the token hashes in place; the row is the revocable "connected app".

type OAuthGrantMetadata

type OAuthGrantMetadata struct {
	ID         int64
	ClientName string
	Scope      string
	CreatedAt  time.Time
	LastUsedAt time.Time
	ExpiresAt  time.Time
}

OAuthGrantMetadata is what an account owner sees about a grant.

type OAuthPrincipalStore

type OAuthPrincipalStore interface {
	OAuthPrincipal(context.Context, [32]byte, time.Time) (Principal, error)
}

OAuthPrincipalStore resolves a live OAuth access token hash.

type OAuthRequestLimiter

type OAuthRequestLimiter interface {
	AllowOAuthRequest(ctx context.Context, remoteAddr, endpoint string, now time.Time) (bool, error)
}

OAuthRequestLimiter enforces shared registration, token and revocation budgets.

type OAuthRotation

type OAuthRotation struct {
	AccessHash          [32]byte
	AccessExpiresAt     time.Time
	RefreshHash         [32]byte
	Now                 time.Time
	Grace               time.Duration
	Audit               audit.Event
	RepositoryIDs       []int64
	ReplaceRepositories bool
	Revoke              bool
}

OAuthRotation carries all writes committed by a successful refresh. Grace suppresses grant revocation for consumed-token retries after rotation. Such retries still fail; a lost refresh response requires fresh authorization. ReplaceRepositories applies a verified GitHub snapshot in the same transaction. Revoke instead revokes only the grant currently owning the presented token; consumed tokens return pgx.ErrNoRows without replay handling.

type OAuthStore

type OAuthStore interface {
	OAuthRequestLimiter
	CreateOAuthClient(context.Context, OAuthClient) error
	OAuthClient(ctx context.Context, id string, now time.Time) (OAuthClient, error)

	CreateOAuthAuthorizationRequest(context.Context, OAuthAuthorizationRequest) error
	// OAuthAuthorizationRequest loads a live request without consuming it.
	OAuthAuthorizationRequest(ctx context.Context, id [32]byte, phase string, now time.Time) (OAuthAuthorizationRequest, error)
	// IssueOAuthCode consumes a pending request using the user's live consent session.
	IssueOAuthCode(ctx context.Context, pendingID, codeID, sessionHash [32]byte, userID int64, expiresAt, now time.Time) error
	DeleteOAuthAuthorizationRequest(ctx context.Context, id [32]byte) error
	// ExchangeOAuthCode atomically consumes a live code and creates its grant,
	// serialized with user credential revocation. Missing or used codes, mismatched
	// grant ownership/scope, and inactive users return pgx.ErrNoRows.
	ExchangeOAuthCode(ctx context.Context, codeID [32]byte, grant OAuthGrant) (int64, error)
	// OAuthPrincipal resolves a live access token to the user's principal and
	// bumps last_used_at.
	OAuthPrincipal(ctx context.Context, accessHash [32]byte, now time.Time) (Principal, error)
	// RotateOAuthGrant rotates the tokens of the grant owning refreshHash.
	// A consumed refresh token returns pgx.ErrNoRows without revoking the grant
	// within rotation.Grace of its consumption; at or after that deadline,
	// the grant is revoked and ErrOAuthReplay is returned.
	RotateOAuthGrant(ctx context.Context, refreshHash [32]byte, rotation OAuthRotation) (OAuthGrant, error)
	// OAuthGrantByRefresh loads the grant owning a current refresh token.
	OAuthGrantByRefresh(ctx context.Context, refreshHash [32]byte, now time.Time) (OAuthGrant, error)
	UpdateOAuthGrantGitHubToken(ctx context.Context, grantID int64, ciphertext []byte) error
	RevokeOAuthGrant(ctx context.Context, grantID int64) error
	// RevokeOAuthGrantByToken revokes the grant owning either token hash when
	// it belongs to clientID and reports whether a grant was newly revoked.
	// Unknown tokens are not an error (RFC 7009).
	RevokeOAuthGrantByToken(ctx context.Context, hash [32]byte, clientID string) (bool, error)
	ListOAuthGrants(ctx context.Context, userID, afterID int64, limit int) ([]OAuthGrantMetadata, bool, error)
	RevokeUserOAuthGrant(ctx context.Context, userID, grantID int64) error
	ReplaceGitHubGrants(ctx context.Context, userID int64, repositoryIDs []int64) error
}

OAuthStore is the persistence contract of the authorization server.

type OAuthTokenAuthenticator

type OAuthTokenAuthenticator struct {
	Store OAuthPrincipalStore
	Now   func() time.Time
}

OAuthTokenAuthenticator authenticates bearer credentials issued by the MCP authorization server.

func (OAuthTokenAuthenticator) Authenticate

func (a OAuthTokenAuthenticator) Authenticate(ctx context.Context, token string) (Principal, error)

type PasswordCredential

type PasswordCredential struct {
	Salt, Hash    []byte
	MemoryKiB     uint32
	Iterations    uint32
	Parallelism   uint8
	ForceRotation bool
}

func HashPassword

func HashPassword(password []byte, random io.Reader) (credential PasswordCredential, err error)

func (PasswordCredential) Validate

func (credential PasswordCredential) Validate() error

type PreparedSession

type PreparedSession struct {
	Token     string
	ExpiresAt time.Time
	Record    SessionRecord
}

type Principal

type Principal struct {
	Subject       string
	Method        string
	Administrator bool
	// DelegationOnly marks an administrator API token that may only mint
	// narrowed, short-lived tokens (POST /v1/admin/api-tokens) for any active
	// repository. It carries no repository access of its own and is refused
	// by every other endpoint, so a leaked broker credential cannot read,
	// search, or upload anything directly.
	DelegationOnly bool
	// Delegated marks an API token minted by the delegation endpoint. It is
	// an ordinary scoped token in every other respect, but it may not
	// delegate again: otherwise each generation could choose a fresh expiry
	// and a stolen child could be rotated indefinitely after its parent was
	// revoked or expired.
	Delegated       bool
	ForceRotation   bool
	InstallationID  int64
	RepositoryIDs   []int64
	RepositoryNames []string
}

func FreshPrincipal added in v0.5.0

func FreshPrincipal(ctx context.Context, fallback Principal) (Principal, error)

type ProvisioningAuthenticator

type ProvisioningAuthenticator struct{ Expected [32]byte }

func NewProvisioningAuthenticator

func NewProvisioningAuthenticator(secret []byte) (ProvisioningAuthenticator, error)

func (ProvisioningAuthenticator) Authenticate

func (a ProvisioningAuthenticator) Authenticate(headerValues []string) error

type RequestAuthenticator

type RequestAuthenticator struct {
	Bearer  Authenticator
	Session interface {
		Authenticate(context.Context, string) (Principal, error)
	}
	PublicOrigin string
	Metrics      *observability.Metrics
}

func (RequestAuthenticator) AuthenticateRequest

func (a RequestAuthenticator) AuthenticateRequest(request *http.Request) (Principal, error)

type SessionManager

type SessionManager struct {
	Store     SessionStore
	IdleTTL   time.Duration
	TTL       time.Duration
	Now       func() time.Time
	Rand      io.Reader
	AuditRand io.Reader
	Audit     audit.Recorder
}

func (SessionManager) Authenticate

func (m SessionManager) Authenticate(ctx context.Context, token string) (Principal, error)

func (SessionManager) Create

func (m SessionManager) Create(ctx context.Context, identity Identity, loginOperation string) (string, time.Time, error)

func (SessionManager) CreateForUser

func (m SessionManager) CreateForUser(ctx context.Context, userID int64, provider string, forceRotation bool) (string, time.Time, error)

func (SessionManager) PrepareForUser

func (m SessionManager) PrepareForUser(userID int64, provider string, forceRotation bool) (PreparedSession, error)

func (SessionManager) Revoke

func (m SessionManager) Revoke(ctx context.Context, token string) error

type SessionRecord

type SessionRecord struct {
	TokenHash                                       [32]byte
	AuditID                                         string
	UserID                                          int64
	Provider                                        string
	ForceRotation                                   bool
	CreatedAt, LastSeenAt, IdleExpiresAt, ExpiresAt time.Time
}

type SessionStore

type SessionStore interface {
	BindFederatedUser(context.Context, string, string, string) (int64, error)
	CreateLoginFlow(context.Context, LoginFlow) error
	ConsumeLoginFlow(context.Context, [32]byte, [32]byte, string, time.Time) (LoginFlow, error)
	CreateSession(context.Context, SessionRecord) error
	CreateSessionAudited(context.Context, SessionRecord, audit.Event) error
	CreateFederatedSessionAudited(context.Context, Identity, SessionRecord, string) error
	SessionPrincipal(context.Context, [32]byte, time.Time, time.Time) (Principal, error)
	RevokeSession(context.Context, [32]byte) error
	RevokeSessionAudited(context.Context, [32]byte) error
	DeleteExpiredAuth(context.Context, time.Time) (flows, sessions int64, err error)
}

type Static

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

func NewStatic

func NewStatic(principals map[string]Principal) *Static

func (*Static) Authenticate

func (auth *Static) Authenticate(_ context.Context, token string) (Principal, error)

type TokenManager

type TokenManager struct {
	Store APITokenStore
	Now   func() time.Time
	Rand  io.Reader
	Audit audit.Recorder
}

func (TokenManager) Authenticate

func (m TokenManager) Authenticate(ctx context.Context, plaintext string) (Principal, error)

func (TokenManager) Create

func (m TokenManager) Create(ctx context.Context, userID int64, repositoryIDs []int64, expiresAt *time.Time) (int64, string, error)

func (TokenManager) CreateDelegated added in v0.5.0

func (m TokenManager) CreateDelegated(ctx context.Context, userID int64, method string, repositoryIDs []int64, expiresAt *time.Time) (int64, string, error)

CreateDelegated mints the child token the delegation endpoint hands out: a scoped token that is marked so it can never delegate in turn.

func (TokenManager) CreateDelegationOnly added in v0.5.0

func (m TokenManager) CreateDelegationOnly(ctx context.Context, userID int64, method string, expiresAt *time.Time) (int64, string, error)

CreateDelegationOnly mints a token with no repository ceiling that only the delegation endpoint honours. Callers must have verified the owner is an interactive administrator; the store rejects the token for anyone else.

func (TokenManager) CreateWithMethod

func (m TokenManager) CreateWithMethod(ctx context.Context, userID int64, method string, repositoryIDs []int64, expiresAt *time.Time) (int64, string, error)

Jump to

Keyboard shortcuts

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