outbound

package
v0.3.20 Latest Latest
Warning

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

Go to latest
Published: Nov 22, 2026 License: Apache-2.0 Imports: 19 Imported by: 1 module, 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

Overview

Package outbound holds credentials an app uses to call third-party APIs on its own or for its users, as opposed to signing people in to the app. Each source is an oauth2.TokenSource, so oauth2.NewClient turns it into an *http.Client and any HTTP-based SDK can use it.

  • GitHubAppInstallation mints a GitHub App's JWT and trades it for an installation token, cached until shortly before it expires.
  • StoredUserToken is a person's token from a connect flow, kept sealed in a UserTokenStore and refreshed (and written back) when it expires.
  • Static is a fixed secret such as a personal access token, read from a SecretRef so it never appears in config.

See docs/OUTBOUND_CREDENTIALS.md for the design and the threat notes.

Index

Constants

View Source
const DefaultGitHubAPI = "https://api.github.com"

DefaultGitHubAPI is the API base for github.com. GitHub Enterprise Server uses https://HOST/api/v3.

View Source
const DefaultRaceWait = 2 * time.Second

DefaultRaceWait is UserTokens.RaceWait's default.

View Source
const DefaultRefreshBefore = 5 * time.Minute

DefaultRefreshBefore is how long before expiry a cached token is replaced. GitHub installation tokens last an hour; five minutes keeps a token handed out now from expiring during a slow request or clone.

View Source
const UserTokenPurpose = "oneauth-outbound-user-token-v1"

UserTokenPurpose is the HKDF label UserTokens derives its AES key with, so the same master key as an EncryptedKeyStorage gives a different key.

Variables

View Source
var ErrNoRevoker = errors.New("outbound: no revoker configured")

ErrNoRevoker is returned by UserTokens.Revoke when UserTokens.Revoker is nil. Delete removes a token without revoking it.

View Source
var ErrReconnect = errors.New("outbound: user token needs a new connect")

ErrReconnect means the stored token can't be renewed without the person: it expired with no refresh token, or the provider refused the refresh token. The app sends the person back through the connect flow.

View Source
var ErrSecretMissing = errors.New("outbound: secret not found")

ErrSecretMissing is returned by Resolve when the variable is unset, the file can't be read, or either holds only whitespace. The error names the reference and never the value.

View Source
var ErrUserTokenNotFound = errors.New("outbound: user token not found")

ErrUserTokenNotFound is returned by GetUserToken when there is no record for the key. To a caller it means the person hasn't connected.

View Source
var ErrVersionConflict = errors.New("outbound: user token version conflict")

ErrVersionConflict is returned by PutUserToken when the stored version isn't ExpectedVersion: another writer got there first. The caller re-reads rather than retrying the write blind.

Functions

func ParseRSAPrivateKeyPEM

func ParseRSAPrivateKeyPEM(keyPEM []byte) (*rsa.PrivateKey, error)

ParseRSAPrivateKeyPEM reads a PKCS#1 or PKCS#8 RSA private key of at least utils.MinRSAKeyBits.

Types

type DeleteUserTokenRequest

type DeleteUserTokenRequest struct {
	Provider string
	Subject  string
}

DeleteUserTokenRequest is the input to UserTokenStore.DeleteUserToken.

type DeleteUserTokenResponse

type DeleteUserTokenResponse struct{}

DeleteUserTokenResponse is the output of UserTokenStore.DeleteUserToken.

type GetUserTokenRequest

type GetUserTokenRequest struct {
	Provider string
	Subject  string
}

GetUserTokenRequest is the input to UserTokenStore.GetUserToken.

type GetUserTokenResponse

type GetUserTokenResponse struct {
	Record *UserTokenRecord
}

GetUserTokenResponse carries the stored record.

type GitHubAPIError

type GitHubAPIError struct {
	StatusCode int
	Message    string
}

GitHubAPIError is a non-success answer from the GitHub API. Message is GitHub's own message. The JWT, the key and any token stay out of it.

func (*GitHubAPIError) Error

func (e *GitHubAPIError) Error() string

type GitHubAppInstallation

type GitHubAppInstallation struct {
	// AppID is the JWT's iss: the App's numeric ID or its Client ID
	// ("Iv1..."). GitHub accepts either.
	AppID string

	// InstallationID names the installation, from the installation webhook
	// or GET /app/installations.
	InstallationID int64

	// Key is the App's RSA private key, at least 2048 bits.
	Key *rsa.PrivateKey

	// BaseURL is the REST API base. Empty means DefaultGitHubAPI.
	BaseURL string

	// Repositories and Permissions narrow the token below what the
	// installation grants, as GitHub's request body allows. Empty means the
	// installation's full grant.
	Repositories []string
	Permissions  map[string]string

	// HTTPClient makes the exchange. Nil means http.DefaultClient. Token
	// has no context, so set a Timeout here.
	HTTPClient *http.Client

	// RefreshBefore overrides DefaultRefreshBefore.
	RefreshBefore time.Duration

	// Now overrides time.Now, for tests.
	Now func() time.Time
	// contains filtered or unexported fields
}

GitHubAppInstallation is a TokenSource for one installation of a GitHub App. Token signs a short RS256 JWT with the App's private key, posts it to /app/installations/{id}/access_tokens, and caches the token until RefreshBefore ahead of its expires_at. Concurrent callers share one fetch.

Set the fields before the first Token call and don't change them after.

See: https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation

func NewGitHubAppInstallation

func NewGitHubAppInstallation(appID string, installationID int64, keyPEM []byte) (*GitHubAppInstallation, error)

NewGitHubAppInstallation parses keyPEM and returns a source for the installation. GitHub hands out App keys as PKCS#1 ("RSA PRIVATE KEY"); PKCS#8 is accepted too.

func (*GitHubAppInstallation) AppJWT

func (g *GitHubAppInstallation) AppJWT() (string, error)

AppJWT signs the App's JWT: iat 60 seconds in the past for clock drift, exp 9 minutes ahead (GitHub allows at most 10), iss AppID. Callers use it directly for /app endpoints, such as listing installations.

func (*GitHubAppInstallation) Invalidate

func (g *GitHubAppInstallation) Invalidate()

Invalidate drops the cached token, so the next Token call fetches a new one. Call it when the API answers 401 with a token that should still be live, as after the installation is suspended and restored.

func (*GitHubAppInstallation) Token

func (g *GitHubAppInstallation) Token() (*oauth2.Token, error)

Token returns the cached installation token, or fetches a new one when none is cached or the cached one is within RefreshBefore of expiry. The returned Expiry is RefreshBefore ahead of GitHub's (see copyCached).

func (*GitHubAppInstallation) TokenContext

func (g *GitHubAppInstallation) TokenContext(ctx context.Context) (*oauth2.Token, error)

TokenContext is Token with a context for the exchange request. Callers waiting on another caller's fetch wait for it under that caller's context.

type GitHubRevoker added in v0.3.6

type GitHubRevoker struct {
	ClientID     string
	ClientSecret string

	// BaseURL is the REST API base. Empty means DefaultGitHubAPI.
	BaseURL string

	// RevokeGrant revokes the whole authorization rather than one token.
	RevokeGrant bool

	// HTTPClient makes the request. Nil means http.DefaultClient.
	HTTPClient *http.Client
}

GitHubRevoker revokes GitHub user tokens through the OAuth app endpoints, authenticated with the app's client ID and secret.

By default it calls DELETE /applications/{client_id}/token, which revokes the one token. With RevokeGrant it calls DELETE /applications/{client_id}/grant instead, which also removes the person's authorization of the app and every token it issued to them, so the next connect shows the consent screen again.

Only 204 counts as success. GitHub answers 404 both for a token that is already revoked and for wrong client credentials (checked by make testgh), so a 404 can't be read as "already revoked" and is an error. UserTokens.Revoke stays idempotent anyway, since it deletes the record after a revoke and finds nothing to revoke the second time.

See: https://docs.github.com/en/rest/apps/oauth-applications

func (*GitHubRevoker) RevokeToken added in v0.3.6

RevokeToken sends the access token to GitHub's revoke endpoint. Failures come back as *GitHubAPIError with GitHub's message, never the token or the client secret.

type MemoryUserTokenStore

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

MemoryUserTokenStore is an in-process UserTokenStore for tests and single-process tools. It loses everything on restart.

func NewMemoryUserTokenStore

func NewMemoryUserTokenStore() *MemoryUserTokenStore

NewMemoryUserTokenStore returns an empty store.

func (*MemoryUserTokenStore) DeleteUserToken

DeleteUserToken removes the record if present.

func (*MemoryUserTokenStore) GetUserToken

GetUserToken returns a copy of the record, or ErrUserTokenNotFound.

func (*MemoryUserTokenStore) PutUserToken

PutUserToken writes under the store's lock, so the version check and the write are atomic.

type PutUserTokenRequest

type PutUserTokenRequest struct {
	Provider string
	Subject  string
	Sealed   []byte

	// ExpectedVersion is the version the caller read. Zero means "create":
	// the write fails with ErrVersionConflict if a record exists.
	ExpectedVersion int64
}

PutUserTokenRequest is the input to UserTokenStore.PutUserToken.

type PutUserTokenResponse

type PutUserTokenResponse struct {
	Version int64
}

PutUserTokenResponse carries the version the store wrote.

type RevokeTokenRequest added in v0.3.6

type RevokeTokenRequest struct {
	// Token is the stored token, with its access and refresh tokens.
	Token *oauth2.Token
}

RevokeTokenRequest is the input to TokenRevoker.RevokeToken.

type RevokeTokenResponse added in v0.3.6

type RevokeTokenResponse struct{}

RevokeTokenResponse is the output of TokenRevoker.RevokeToken.

type SecretRef

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

SecretRef names where a secret lives, never the secret itself. Two forms are accepted:

env:NAME      the environment variable NAME
file:PATH     the contents of the file at PATH (a mounted secret)

PATH is absolute: /run/secrets/app.pem, or C:\secrets\app.pem on Windows.

Anything else is refused by ParseSecretRef, including a bare value, so a token pasted into config fails at startup instead of being stored there.

func MustParseSecretRef

func MustParseSecretRef(s string) SecretRef

MustParseSecretRef is ParseSecretRef for literals in code and tests. It panics on an invalid reference.

func ParseSecretRef

func ParseSecretRef(s string) (SecretRef, error)

ParseSecretRef parses "env:NAME" or "file:PATH". PATH must start with "/" or be absolute by filepath.IsAbs, so a reference means the same thing whatever the working directory is. On Windows that admits C:\path and \\server\share\path, and refuses C:path, which depends on the current directory of drive C. A path starting with "/" is accepted on every OS.

func (SecretRef) IsZero

func (r SecretRef) IsZero() bool

IsZero reports whether r is the zero SecretRef.

func (SecretRef) Resolve

func (r SecretRef) Resolve() (string, error)

Resolve reads the secret each time it is called, so a rotated file or variable takes effect without a restart. Surrounding whitespace is trimmed, as mounted secrets often end in a newline.

func (SecretRef) String

func (r SecretRef) String() string

String returns the reference in the form ParseSecretRef accepts. It is safe to log.

type Static

type Static struct {
	Ref SecretRef

	// TokenType is the Authorization scheme. Empty means "Bearer", which
	// GitHub, S3-compatible gateways and most APIs accept.
	TokenType string
}

Static is a TokenSource for a fixed bearer secret, such as a GitHub personal access token. The secret comes from Ref on every Token call, so rotating the file or variable needs no restart. The token has no expiry, and Static never caches it.

func NewStatic

func NewStatic(ref string) (*Static, error)

NewStatic parses ref and checks it resolves now, so a missing secret fails at startup rather than on the first API call.

func (*Static) Token

func (s *Static) Token() (*oauth2.Token, error)

Token resolves Ref. A secret that has gone missing is ErrSecretMissing.

type StoredUserToken

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

StoredUserToken is a TokenSource for one person's stored token. Each Token call reads the store, so a token saved or refreshed by another replica is seen at once.

func (*StoredUserToken) Token

func (s *StoredUserToken) Token() (*oauth2.Token, error)

Token is TokenContext with a background context.

func (*StoredUserToken) TokenContext

func (s *StoredUserToken) TokenContext(ctx context.Context) (*oauth2.Token, error)

TokenContext returns the stored token, refreshing it first when it is within RefreshBefore of expiry. Errors:

  • ErrUserTokenNotFound: the person hasn't connected.
  • ErrReconnect: the token expired with no refresh token, or the provider refused the refresh token and no other replica had stored a newer one.
  • keys.ErrSealedOpen (wrapped): the record doesn't open with this master key, or was moved from another person's record.

When the refresh races another replica's, the loser returns the winner's stored token. When it races a Delete or Revoke, it returns ErrUserTokenNotFound and the record stays deleted. The returned Expiry is RefreshBefore ahead of the provider's, as for GitHubAppInstallation.

type TokenRevoker added in v0.3.6

type TokenRevoker interface {
	RevokeToken(ctx context.Context, req *RevokeTokenRequest) (*RevokeTokenResponse, error)
}

TokenRevoker revokes a person's token at its provider, so it stops working even if a copy exists outside the store. It returns nil only when the provider confirms the revocation.

type UserTokenRecord

type UserTokenRecord struct {
	// Provider names the service, such as "github". Together with Subject
	// it is the record's key.
	Provider string

	// Subject names the person in the app, normally the app's user ID.
	Subject string

	// Sealed is the token, sealed by UserTokens under AAD naming Provider
	// and Subject.
	Sealed []byte

	// Version starts at 1 and goes up by one on every write. Stores set
	// it; callers pass the version they read as ExpectedVersion.
	Version int64

	// UpdatedAt is when the store last wrote the record.
	UpdatedAt time.Time
}

UserTokenRecord is one person's token for one provider, as a store keeps it. Sealed is opaque ciphertext from UserTokens; a store never sees the token itself.

type UserTokenStore

type UserTokenStore interface {
	// GetUserToken returns the record, or ErrUserTokenNotFound.
	GetUserToken(ctx context.Context, req *GetUserTokenRequest) (*GetUserTokenResponse, error)

	// PutUserToken writes the record if the stored version equals
	// ExpectedVersion (zero meaning no record exists), and answers
	// ErrVersionConflict otherwise. The check and the write are atomic
	// per record.
	PutUserToken(ctx context.Context, req *PutUserTokenRequest) (*PutUserTokenResponse, error)

	// DeleteUserToken removes the record. Deleting a missing record is
	// not an error, so disconnecting twice is safe.
	DeleteUserToken(ctx context.Context, req *DeleteUserTokenRequest) (*DeleteUserTokenResponse, error)
}

UserTokenStore keeps sealed user tokens with compare-and-swap writes.

The compare-and-swap is what keeps refresh safe across replicas. GitHub and most providers rotate the refresh token on every use, and the old one stops working. If two replicas refresh the same token and both write, the store can end up with the loser's refresh token, which the provider has already refused. With CAS the loser's write fails and it reads the winner's token instead.

usertokentest.RunAll checks an implementation against this contract.

type UserTokens

type UserTokens struct {
	// Provider is the record key's provider half, such as "github".
	Provider string

	// Store holds the sealed records.
	Store UserTokenStore

	// Config is the OAuth client the tokens were issued to. Only
	// ClientID, ClientSecret and Endpoint.TokenURL are used, to refresh.
	Config *oauth2.Config

	// HTTPClient makes refresh requests. Nil means http.DefaultClient.
	HTTPClient *http.Client

	// RefreshBefore is how long before expiry a token is refreshed. Zero
	// means DefaultRefreshBefore.
	RefreshBefore time.Duration

	// Revoker revokes a token at the provider for Revoke. Nil means
	// Revoke answers ErrNoRevoker; Delete works either way.
	Revoker TokenRevoker

	// RaceWait is how long a replica whose refresh the provider refused
	// waits for another replica's refreshed token to appear in the store
	// before answering ErrReconnect. The winner's write follows its
	// refresh by one store round trip, so a refusal can arrive first.
	// Zero means DefaultRaceWait.
	RaceWait time.Duration

	// Now overrides time.Now, for tests.
	Now func() time.Time
	// contains filtered or unexported fields
}

UserTokens keeps people's tokens for one provider, sealed in a UserTokenStore, and hands out a StoredUserToken per person. Use one per provider, built with NewUserTokens.

Typical use: the connect flow's HandleUserFunc calls Save with the token it was given, and code calling the API later uses TokenSource(subject).

func NewUserTokens

func NewUserTokens(provider string, store UserTokenStore, masterKeyHex string, cfg *oauth2.Config) (*UserTokens, error)

NewUserTokens returns a UserTokens sealing with an AES key derived from masterKeyHex (64 hex characters) under UserTokenPurpose.

func (*UserTokens) Delete

func (u *UserTokens) Delete(ctx context.Context, subject string) error

Delete removes subject's token without revoking it at the provider. Revoke does both.

func (*UserTokens) Revoke added in v0.3.6

func (u *UserTokens) Revoke(ctx context.Context, subject string) error

Revoke disconnects subject: it revokes the stored token at the provider with Revoker, then deletes the record. Errors:

  • nil when there is no record, since there is nothing to revoke.
  • ErrNoRevoker when Revoker is nil. The record is kept.
  • keys.ErrSealedOpen (wrapped) when the record doesn't open. The record is kept, since the token may still be live at the provider; Delete removes it anyway.
  • the revoker's error when the provider refuses. The record is kept, so Revoke can be retried.

It holds the same per-subject lock as StoredUserToken, so a refresh in this process can't write a new token back after the revoke.

func (*UserTokens) Save

func (u *UserTokens) Save(ctx context.Context, subject string, tok *oauth2.Token) error

Save stores tok for subject, replacing any token already there. A connect flow calls it, so it overwrites whatever version it finds, retrying a few times if a refresh writes in between.

func (*UserTokens) TokenSource

func (u *UserTokens) TokenSource(subject string) *StoredUserToken

TokenSource returns subject's StoredUserToken. It does no I/O; a person who hasn't connected shows up as ErrUserTokenNotFound from Token.

Directories

Path Synopsis
Package githubtest is a fake GitHub for tests of code using outbound.GitHubAppInstallation and outbound.StoredUserToken.
Package githubtest is a fake GitHub for tests of code using outbound.GitHubAppInstallation and outbound.StoredUserToken.

Jump to

Keyboard shortcuts

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