creds

package
v3.0.0-dev.6 Latest Latest
Warning

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

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

Documentation

Overview

Package creds is the credential machinery behind a forgeapi connection: stored credentials, a personal access token or a rotating OAuth grant with its refresh machine, device grant and store, over a file or over a backend the consumer supplies; and derived ones, a GitHub App's installation tokens, minted from its key.

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, saves the record under the consumer's own key, and runs a client behind the source that keeps that credential fresh, so the client never holds a token.

It has no Output comment, so it is compiled and not run: running it would open a real grant against github.com.

package main

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

	"github.com/cplieger/forgeapi/v3"
	"github.com/cplieger/forgeapi/v3/creds"
	"github.com/cplieger/forgeapi/v3/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.NewStoredSource(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 AppGrant

type AppGrant struct {
	// Permissions maps a permission name to its level, "read", "write" or
	// "admin", such as "metadata": "read".
	Permissions map[string]string
	// Repositories are repository names under the installation's account, at
	// most 500; none means every repository the installation can reach.
	Repositories []string
	// contains filtered or unexported fields
}

AppGrant is what an installation token may do: the named permissions, optionally over named repositories, or the installation's full grant through FullGrant. The zero value grants nothing and is refused.

func FullGrant

func FullGrant() AppGrant

FullGrant asks for everything the installation holds, by name, so a forgotten field can never ask for it.

type AppKey

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

AppKey is one GitHub App's identity: the issuer GitHub names it by, and the signer holding its private key. It signs the App's JWT and nothing else, and no error, log line or method answers the key. It is safe for concurrent use where its signer is. The zero value is not usable: build one with NewAppKey or ParseAppKeyPEM.

func NewAppKey

func NewAppKey(issuer string, signer crypto.Signer) (*AppKey, error)

NewAppKey builds the key of the App GitHub names issuer, its client ID or its numeric App ID, signing through signer, so a key held in a KMS or HSM never enters the process. It refuses with forgeapi.CodeAppKeyInvalid an issuer that is empty or holds whitespace or a non-printable character, a nil signer, and a signer whose public key is not RSA or is under 2048 bits.

func ParseAppKeyPEM

func ParseAppKeyPEM(issuer string, pemBytes []byte) (*AppKey, error)

ParseAppKeyPEM builds the key of the App GitHub names issuer from the private key file GitHub issued it: one PEM block holding a PKCS #1 or PKCS #8 RSA key. It refuses with forgeapi.CodeAppKeyInvalid whatever NewAppKey refuses, and PEM that is malformed, holds anything after its one block, or holds any other kind of key. No refusal quotes the input.

func (*AppKey) JWT

func (k *AppKey) JWT(ctx context.Context) (string, error)

JWT answers a fresh RS256 App JWT: iss the issuer, iat 60 seconds in the past, exp 9 minutes ahead. Its signature matches actions/scaleset's JWTProviderFunc, so scaleset.JWTProviderFunc(key.JWT) is that package's JWTProvider. It fails with ctx's error where ctx has ended, and as transient and retryable where the signer fails.

type AppSource

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

AppSource is the forgeapi.CredentialSource of one GitHub App installation. It mints an installation token on first use, hands it out until the refresh lead before its expiry, then mints again under one owner while other callers wait, bounded by their own contexts. A refusal only a human can repair reads forgeapi.CredReconnectRequired, re-probed after 5 minutes doubling to an hour; a rate limit stops every request for its wait; an unclassified refusal waits a minute, doubling to 15; a 5xx, a lost connection or an unreadable answer is retried within the budget. It is safe for concurrent use.

Example

ExampleAppSource runs a client as a GitHub App installation and mints a token for a child process that reads it once. It is compiled and not run: running it would mint against github.com.

package main

import (
	"context"
	"fmt"
	"os"
	"time"

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

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

	pemBytes, err := os.ReadFile("/etc/example/app-private-key.pem")
	if err != nil {
		fmt.Println(err)
		return
	}
	key, err := creds.ParseAppKeyPEM("your-app-client-id", pemBytes)
	if err != nil {
		fmt.Println(err)
		return
	}

	// The grant says what each token may do, here read pull requests on
	// your-repo.
	src, err := creds.NewAppSource(conn, key, creds.AppSourceConfig{
		Installation: creds.InstallationOfRepo("your-org/your-repo"),
		Grant: creds.AppGrant{
			Permissions:  map[string]string{"metadata": "read", "pull_requests": "read"},
			Repositories: []string{"your-repo"},
		},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	client, err := github.New(conn, forgeapi.WithCredentialSource(src))
	if err != nil {
		fmt.Println(err)
		return
	}
	defer client.Close()

	// An installation token cannot list GET /user/repos, so the list names the
	// installation's account. Each RepoRef comes from that answer.
	repos, err := client.ListRepos(ctx, forgeapi.WithOwner("your-org"))
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, repo := range repos.Items {
		prs, err := client.ListPRs(ctx, repo.Ref, forgeapi.WithState(forgeapi.ListStateOpen))
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(repo.Ref.DisplayPath, len(prs.Items), "open pull requests")
	}

	tok, err := src.Mint(ctx)
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("token valid until", tok.Expiry.Format(time.RFC3339))
}

func NewAppSource

func NewAppSource(conn forgeapi.Connection, key *AppKey, cfg AppSourceConfig, opts ...forgeapi.Option) (*AppSource, error)

NewAppSource builds the source for the installation cfg names, signing with key and minting through conn as a client would, with opts' lead, logger, counters and budget; it copies the grant and sends nothing. It refuses what NewStoredSource refuses, a nil key with forgeapi.CodeAppKeyInvalid, a config it cannot send with forgeapi.CodeAppGrantInvalid, and a plaintext base with forgeapi.CodePlaintextRefused even under forgeapi.WithPlaintextHTTP.

func (*AppSource) Discard

func (s *AppSource) Discard(token string) (retry bool)

Discard is called after a request that used token was answered 401. A cached token minted under 5 seconds earlier is kept and Discard answers true: the 401 is GitHub's replication delay, so the caller retries it. Otherwise it drops the cached token when it is still token and answers false, and the next Token mints; but a token dropped under a minute after its mint makes Token and Mint fail at once with forgeapi.KindUnauthorized and RetryAfter for 5 minutes, doubling to an hour per further early drop, until a token is handed out past its first minute.

func (*AppSource) Kind

func (*AppSource) Kind() forgeapi.CredKind

Kind answers forgeapi.CredKindAppInstallation.

func (*AppSource) Mint

Mint always mints a new token and answers it with its expiry, for handing to a process that reads its token once. It does not replace the cached token. It fails at once, sending nothing, where Token would: after a terminal answer until the re-probe, and during a rate limit's wait.

func (*AppSource) Resolve

func (s *AppSource) Resolve(ctx context.Context) (int64, error)

Resolve answers the installation's ID, looking it up on first call, retried as a mint is, and from memory after, so a consumer can build a client that needs the ID before any token exists. A token request GitHub answers 404 clears the remembered ID, and so does every re-probe after a terminal answer, so a reinstall's new ID is found; an InstallationByID selector keeps its own.

func (*AppSource) State

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

State answers where the source sits without sending anything: reconnect required after a terminal answer until a mint succeeds, valid while the cached token is outside the refresh lead, refreshing while a Token call mints, and refresh-due otherwise, a source that has minted nothing yet included.

func (*AppSource) Token

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

Token answers the cached installation token, minting one first where none is cached or the cached one is inside the refresh lead. A mint that fails hands the cached token over while it has not expired, and fails the call once it has; a waiter fails with its own context's error.

type AppSourceConfig

type AppSourceConfig struct {
	Installation Installation
	Grant        AppGrant
}

AppSourceConfig is what only an App source has: which installation, and what its tokens may do. A zero Grant is refused: a consumer names the permissions it needs, or asks for FullGrant explicitly.

type Backend

type Backend interface {
	// Load answers the record under key, and false with no error where none is.
	Load(key string) (Record, bool, error)
	// Keys answers every key that holds a record, in no stated order.
	Keys() ([]string, error)
	// Put stores rec under key in place of any record there.
	Put(key string, rec Record) error
	// Delete removes the record under key. Deleting a key that holds no record
	// is not an error.
	Delete(key string) error
	// Swap stores next under key only when the stored record is prev, compared
	// with [Record.Equal], and reports whether it did. A key holding no record
	// is not prev.
	Swap(key string, prev, next Record) (bool, error)
}

Backend is the storage under a Store: records by key, and a compare-and-swap a rotation commits through. Every method is durable before it returns, because a rotated pair has no other copy. A failed Swap is retried by a later token call with the same prev and next, so a write that landed before its error is found and kept. It must be safe for concurrent use.

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 with group or other access, or owned by another user, is refused, then and at every later read or write. It reads the logger and the counters from opts.

Exactly one process may refresh from a directory, the one calling StoredSource.Token; readers such as the git credential helper may share it. Nothing detects a second refresher, which can lose a rotated pair.

func (*FileStore) Delete

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

Delete removes the record under key, which is a disconnect. Deleting a key that holds no record is not an error.

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 Installation

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

Installation names the one GitHub App installation an AppSource mints for, in the way its consumer knows it. Build one with InstallationByID, InstallationOfUser, InstallationOfOrg, InstallationOfRepo or OnlyInstallation; the zero value names nothing and is refused.

func InstallationByID

func InstallationByID(id int64) Installation

InstallationByID names the installation by its ID, so no lookup is sent.

func InstallationOfOrg

func InstallationOfOrg(login string) Installation

InstallationOfOrg names the App's installation on the organization login, looked up at GET /orgs/{login}/installation.

func InstallationOfRepo

func InstallationOfRepo(fullName string) Installation

InstallationOfRepo names the App's installation that reaches the repository fullName, spelled owner/repo as GitHub spells it, looked up at GET /repos/{owner}/{repo}/installation.

func InstallationOfUser

func InstallationOfUser(login string) Installation

InstallationOfUser names the App's installation on the user account login, looked up at GET /users/{login}/installation.

func OnlyInstallation

func OnlyInstallation() Installation

OnlyInstallation names the App's one installation, looked up at GET /app/installations, which must list exactly one.

type InstallationToken

type InstallationToken struct {
	Token  masked.Secret
	Expiry time.Time
}

InstallationToken is one minted installation token and the instant GitHub stops honouring it.

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         masked.Secret
	Issued        time.Time     // when the grant or the last rotation answered
	Expiry        time.Time     // zero where the response stated none
	RefreshToken  masked.Secret // zero 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.

func (*Record) Equal

func (r *Record) Equal(o *Record) bool

Equal reports whether r and o are the same record: every field equal, the times as instants with time.Time.Equal, the tokens with masked.Secret.Equal and the scopes in order. It is the comparison Backend.Swap commits a rotation by.

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 a store comes from OpenFileStore or NewStore, and from nowhere else.

func NewStore

func NewStore(b Backend) Store

NewStore returns the Store over b, with the library's custody around it: one rotation per key, the rotated pair held where b could not take it, and the mark owed where b could not take that. The custody lives in the returned store, not in b, so call NewStore once per backend and share the store between every StoredSource over it. Exactly one process may refresh from b, the one calling StoredSource.Token; readers such as the git credential helper may share it. Nothing detects a second store or a second refresher, either of which can lose a rotated pair.

type StoredSource

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

StoredSource 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 NewStoredSource

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

NewStoredSource 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 (*StoredSource) Kind

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

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

func (*StoredSource) State

func (s *StoredSource) 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 (*StoredSource) StoredToken

func (s *StoredSource) StoredToken() (token masked.Secret, state forgeapi.CredState, err error)

StoredToken answers the stored token and the state StoredSource.State reports for it, from one read of the store, never sending, writing or waiting on a refresh. A reconnect-required record fails with forgeapi.CodeReconnectRequired naming why. Where a rotated pair waits to be stored, its token is answered. An expired token whose 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 (*StoredSource) Token

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

Token answers the stored token, refreshing it first where it is due. A failed refresh hands over the still-valid token, failing only once it has expired. A lost or undecodable new pair fails the call and marks the record UsabilitySpent. A new pair the store refused fails with the store's error and is held: the next call stores it first, sending no refresh, unless the record has changed since. A marked or reconnect-required record fails with forgeapi.CodeReconnectRequired naming why; a waiter fails with its context's error. A mark the store refused is written by the next call that can write.

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