creds

package
v2.0.0-dev.10 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

Package creds is the credential machinery behind a forgeapi connection: the refresh state machine a rotating OAuth credential runs under, the OAuth device grant that mints one, and the file-backed store both of them read.

The vocabulary it implements, forgeapi.CredentialSource, forgeapi.CredKind and forgeapi.CredState, is the root package's. Nothing here reads the environment and no goroutine or timer runs here: a consumer keeps a credential fresh by calling Token, which every operation it issues already does.

Example

Example signs a user in to github.com through the OAuth device grant, stores the credential the grant answers, and runs a client behind the source that keeps that credential fresh. It is the whole lifecycle a consumer wires: render the user code, poll at the interval the grant states, save the record under the consumer's own key for the connection, and hand the client a source over that key rather than a token.

The example carries no Output comment, so the toolchain compiles it and does not run it: running it would open a real grant against github.com.

package main

import (
	"context"
	"errors"
	"fmt"
	"time"

	"github.com/cplieger/forgeapi/v2"
	"github.com/cplieger/forgeapi/v2/creds"
	"github.com/cplieger/forgeapi/v2/github"
)

func main() {
	ctx := context.Background()
	conn := forgeapi.Connection{WebBaseURL: "https://github.com"}

	// The store is one file in a directory this process owns, at an absolute path
	// the consumer chooses.
	store, err := creds.OpenFileStore("/var/lib/example/credentials")
	if err != nil {
		fmt.Println(err)
		return
	}

	// The client id is the consumer's own OAuth application's.
	grant, err := creds.StartDeviceGrant(ctx, conn, forgeapi.FamilyGitHub, creds.GrantRequest{
		ClientID: "your-oauth-app-client-id",
		Scopes:   []string{"repo"},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("Open %s and enter %s\n", grant.VerificationURI, grant.UserCode)

	var rec creds.Record
	timer := time.NewTimer(grant.Interval)
	defer timer.Stop()
	for approved := false; !approved; {
		select {
		case <-ctx.Done():
			fmt.Println(ctx.Err())
			return
		case <-timer.C:
		}
		rec, approved, err = grant.Poll(ctx)
		var ferr *forgeapi.Error
		switch {
		case errors.As(err, &ferr) && (ferr.Code == forgeapi.CodeGrantDenied || ferr.Code == forgeapi.CodeGrantExpired):
			// Both end the grant: start a new one to try again.
			fmt.Println(ferr.Code)
			return
		case err != nil:
			fmt.Println(err)
			return
		}
		// A slow_down answer widens the interval, so the wait is read again.
		timer.Reset(grant.Interval)
	}

	const key = "github.com"
	if err := store.Save(key, rec); err != nil {
		fmt.Println(err)
		return
	}

	// The source refreshes the stored credential before it expires, so the client
	// never holds a token of its own.
	src, err := creds.NewSource(store, key, conn)
	if err != nil {
		fmt.Println(err)
		return
	}
	client, err := github.New(conn, forgeapi.WithCredentialSource(src))
	if err != nil {
		fmt.Println(err)
		return
	}

	me, err := client.Whoami(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("signed in as", me.Login)
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type DeviceGrant

type DeviceGrant struct {
	// UserCode is what the user types at VerificationURI.
	UserCode        string
	VerificationURI string
	// Expires is when the codes expire; a poll after it ends the grant.
	Expires time.Time
	// Interval is how long to wait between polls, widened by slow_down.
	Interval time.Duration
	// contains filtered or unexported fields
}

DeviceGrant is one OAuth device grant in progress: what the consumer renders, and what it polls. The device code stays unexported, because it is a bearer secret for the grant's whole life and nothing a consumer renders needs it. One grant is polled by one loop; DeviceGrant.Close may come from any other goroutine.

func StartDeviceGrant

func StartDeviceGrant(ctx context.Context, conn forgeapi.Connection, family forgeapi.Family, req GrantRequest, opts ...forgeapi.Option) (*DeviceGrant, error)

StartDeviceGrant sends the device-code request for req to conn's web base and answers the grant to render and poll. The Gitea family is refused before any request with forgeapi.CodeGrantUnsupported. The grant's requests go through conn's trust material, proxy and address policy, read from opts as a client's. A caller that abandons the grant before Poll answers a terminal result calls DeviceGrant.Close to release its endpoint.

func (*DeviceGrant) Close

func (g *DeviceGrant) Close()

Close ends a pending grant on the consumer's own word and releases its endpoint, sending nothing: the next Poll answers forgeapi.CodeGrantDenied at status 0, the end being the consumer's and no instance's. On a grant already granted or ended it changes nothing, so Poll keeps answering the record or that end. A Close during a Poll in flight returns after it, and a grant that poll completed stays granted.

func (*DeviceGrant) Poll

func (g *DeviceGrant) Poll(ctx context.Context) (Record, bool, error)

Poll sends one token request and answers the record and true once the user approves, the zero record and false while approval is pending or after slow_down. A denial (forgeapi.CodeGrantDenied), an expiry (forgeapi.CodeGrantExpired) and a success holding no readable token (forgeapi.CodeValidation at its status: a body cut off, undecodable or tokenless, or a lifetime of neither kind) end the grant, since each spends or voids the device code; a context ending inside such a success answers its sentinel. A later Poll answers an end or the record again and sends nothing; a failure status, or no status at all, leaves the grant open.

type FileStore

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

FileStore is the Store over one file, credentials.json at mode 0600, in a directory at mode 0700 this process owns. Every read re-reads the file, so two stores on one directory, a server's and a git credential helper's, each read what the other last wrote. It is safe for concurrent use.

func OpenFileStore

func OpenFileStore(dir string, opts ...forgeapi.Option) (*FileStore, error)

OpenFileStore opens the store in dir, an absolute path, creating that one directory level at 0700 where it is absent. A directory that exists with group or other access, or that another user owns, is refused rather than repaired, and so is every later read or write once it is found that way. It reads the logger and the counters from opts.

A store directory has exactly one refreshing process: the one whose Source.Token calls keep its records fresh. Another process may open the same directory to read it, as the git credential helper does, since a reader never refreshes. Two refreshing processes are outside what the store supports: a terminal answer one meets for a refresh token the other just spent can mark the record before the other stores the pair it rotated, and since a rotation's compare-and-swap is over the whole record, the mark included, that pair is never stored and the connection needs a reconnect. Nothing detects a second refreshing process.

func (*FileStore) Delete

func (s *FileStore) Delete(key string) error

Delete removes the record under key and marks the key's refresh custody gone, freed after its last holder unless a rotated pair or an owed mark is pending.

func (*FileStore) Keys

func (s *FileStore) Keys() ([]string, error)

Keys answers every key that holds a record.

func (*FileStore) Load

func (s *FileStore) Load(key string) (Record, bool, error)

Load answers the record under key, and false with no error where none is.

func (*FileStore) Save

func (s *FileStore) Save(key string, rec Record) error

Save stores rec under key in place of any record there.

type GrantRequest

type GrantRequest struct {
	ClientID string
	Scopes   []string
}

GrantRequest is what a device grant asks for: the consumer's own OAuth application, which the record the grant answers names, and its scopes.

type Record

type Record struct {
	// Family and WebBaseURL are where a refresh is addressed and what the git
	// credential helper matches an origin against.
	Family        forgeapi.Family
	WebBaseURL    string
	Kind          forgeapi.CredKind
	Token         string
	Issued        time.Time // when the grant or the last rotation answered
	Expiry        time.Time // zero where the response stated none
	RefreshToken  string    // empty where the response carried none
	RefreshExpiry time.Time // zero where the response stated none
	ClientID      string    // the OAuth application that minted the grant
	Scopes        []string  // as the response stated them, where it did
	Account       string
	// Usability is the mark a refresh writes when it learns the stored pair can
	// no longer be used, which the kind and the expiry cannot say.
	Usability Usability
}

Record is one connection's stored credential. The consumer saves what a grant answers, or a record it builds for a personal access token; the library writes a record only to rotate it or to mark it. A zero-valued record has the unknown kind and reads as reconnect-required, never as a static token that needs no refresh.

type Source

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

Source is the forgeapi.CredentialSource one connection runs behind: the refresh state machine over the record a store holds under one key. A record is valid until the time left to its expiry is inside the refresh lead, then due, and the next Token refreshes it under the key's one owner in its store while every other caller for that key waits, bounded by its own context. It is safe for concurrent use.

func NewSource

func NewSource(store Store, key string, conn forgeapi.Connection, opts ...forgeapi.Option) (*Source, error)

NewSource builds the source for the record under key in store, refreshing it through conn's trust material, proxy and address policy. It reads the refresh lead, the logger, the counters and the two per-connection postures from opts, sends nothing, and refuses a negative lead with forgeapi.CodeBudgetInvalid and a connection a client could not run with that connection's own refusal.

func (*Source) Kind

func (s *Source) Kind() forgeapi.CredKind

Kind answers the stored record's kind, the unknown member where none is stored or the store cannot be read.

func (*Source) State

func (s *Source) State() forgeapi.CredState

State answers where the stored record sits in the machine without sending anything, and forgeapi.CredUnknown where the store cannot be read. A record whose rotated pair is held for the next call to store is refresh-due, since the connection needs work from the library and not from a human.

func (*Source) StoredToken

func (s *Source) StoredToken() (token string, state forgeapi.CredState, err error)

StoredToken answers the stored token and the state Source.State reports for it, from one read of the store, without sending, writing or waiting on a refresh another call holds. A record State reads as reconnect-required fails with forgeapi.CodeReconnectRequired and a message naming why. Where a rotated pair waits for the next Source.Token call to store it, the pair's token is answered. A token past its expiry while its refresh is due or in flight, or a held pair whose token expired or whose refresh token lapsed, fails as transient and retryable. A store that cannot be read fails with the store's error and forgeapi.CredUnknown.

func (*Source) Token

func (s *Source) Token(ctx context.Context) (string, error)

Token answers the stored token, refreshing it first where it is due. A refresh that fails before the instance issues anything hands the still-valid token over, and fails the call only once that token has expired. A refresh whose new pair could not be read, its body undecodable or lost on the way, fails the call and marks the record UsabilitySpent, because the instance spent the stored pair. A refresh whose new pair the store could not take fails the call with the store's error and holds the pair: the next call for the key stores it before anything else, sending no refresh, and answers from it, unless the stored record is no longer the one the pair was rotated from. A waiter fails with its own context's error. Reconnect-required fails with forgeapi.CodeReconnectRequired, and so does a record marked UsabilitySpent or UsabilityReconnectRequired, with a message naming the mark. What a refresh learns is written to the record, and a mark the store could not take is written by the next call for the key whose write succeeds.

type Store

type Store interface {
	// Load answers the record under key, and false with no error where none is.
	Load(key string) (Record, bool, error)
	// Save stores rec under key in place of any record there: connect and
	// reconnect.
	Save(key string, rec Record) error
	// Delete removes the record under key, which is a disconnect. Deleting a
	// key that holds no record is not an error.
	Delete(key string) error
	// Keys answers every key that holds a record, in no stated order.
	Keys() ([]string, error)
	// contains filtered or unexported methods
}

Store holds the credential records of a consumer's connections under keys that are the consumer's own connection identities, opaque here.

Its unexported methods are a refresh's custody of a key: the single owner a rotation runs under and its compare-and-swap over the whole record. So FileStore is its only implementation.

type Usability

type Usability int

Usability is what a refresh learned about a record's stored pair that the record's other fields cannot say. Every reader of the record honours it, in any process: a marked record is never handed over and never refreshed.

const (
	// UsabilityUnmarked is the zero value: nothing is recorded, so the kind and
	// the expiry decide. A connect or a reconnect saves a record unmarked, which
	// is what clears a mark.
	UsabilityUnmarked Usability = iota
	// UsabilitySpent is a pair the instance rotated whose successor was lost, so
	// the stored token is dead upstream while the record still holds it.
	UsabilitySpent
	// UsabilityReconnectRequired is a pair whose refresh the instance answered
	// terminally.
	UsabilityReconnectRequired
)

The Usability members.

func (Usability) String

func (u Usability) String() string

String returns the member's spelling: "unmarked", "spent" or "reconnect_required". The store's file spells a mark the same way and writes no member for an unmarked record, so "unmarked" is never in a file. A value outside the members reads, and is spelled, as reconnect_required, because an unknown mark must not read as usable.

Jump to

Keyboard shortcuts

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