connections

package
v0.7.21 Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2026 License: Apache-2.0 Imports: 11 Imported by: ? 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

Overview

Package connections names the sign-ins a server holds for third-party services, so a mount over a private repo can read it. Several mounts can share one connection, such as one GitHub App installation over many repos. A connection signs in either as the server or for one person.

A Connection record never holds a secret. It names where the secret is, as an oneauth secret reference ("env:NAME" or "file:/abs/path"), or, for a person's own token, keeps it sealed in oneauth's user-token store. The design and its threat note are at https://panyam.github.io/goapplib/reference/connections/.

Index

Constants

View Source
const DefaultAccessTTL = time.Minute

DefaultAccessTTL is how long CanRead keeps an answer for one viewer and source.

View Source
const LastUsedEvery = time.Hour

LastUsedEvery is how often the service writes a connection's LastUsed. A token request inside that window since the last write doesn't touch the record, so reading a token doesn't cost a store write on every request.

Variables

View Source
var (
	// ErrNotFound means no connection has that ID.
	ErrNotFound = errors.New("connections: not found")

	// ErrInvalid means a record fails Validate: a missing field, a field its Kind doesn't use,
	// or a secret reference that doesn't parse.
	ErrInvalid = errors.New("connections: invalid record")

	// ErrNotOwner means a ScopePerson connection was asked for a token by a request whose
	// viewer isn't its Owner, or by a request with no viewer.
	ErrNotOwner = errors.New("connections: viewer does not own this connection")

	// ErrNotConfigured means the Service lacks what a connection needs, such as a
	// KindGitHubUser connection on a service built without WithUserTokens.
	ErrNotConfigured = errors.New("connections: service not configured for this connection")

	// ErrReconnect means a person's token can't be refreshed, so they have to connect again.
	// It wraps oneauth's outbound.ErrReconnect.
	ErrReconnect = errors.New("connections: connect again")
)

The errors a store and the token-source call return, wrapped with detail. An app maps them onto its own transport with errors.Is. None of them carries a secret.

View Source
var ErrNoAccess = errors.New("connections: no connection of the viewer's can read this source")

ErrNoAccess means none of the viewer's connections can read the source, or the viewer has none to that service.

Functions

func UserTokenProvider

func UserTokenProvider(connectionID string) string

UserTokenProvider is the provider key a KindGitHubUser connection's token is kept under in oneauth's user-token store, beside the owner's subject. Keying by connection, not by "github", lets one person hold two GitHub connections, such as github.com and an Enterprise host.

func Viewer

func Viewer(ctx context.Context) string

Viewer returns the subject WithViewer set, or "" for a request with no person, such as a background job.

func WithViewer

func WithViewer(ctx context.Context, subject string) context.Context

WithViewer returns ctx carrying the subject of the person a request is for. The app sets it from its auth, and a ScopePerson connection gives a token only when it matches Owner.

Types

type Connection

type Connection struct {
	// ID names the connection in mount records. It follows the mount name rule.
	ID string

	Kind  Kind
	Scope Scope

	// Owner is the subject of the person a ScopePerson connection belongs to, as the app's
	// auth knows them. It is empty for ScopeServer.
	Owner string

	// Name is what a settings page shows, such as "acme org (App)".
	Name string

	// BaseURL is the service's API root. Empty means https://api.github.com. GitHub Enterprise
	// and tests set it.
	BaseURL string

	// AppID and InstallationID identify a KindGitHubApp installation.
	AppID          string
	InstallationID int64

	// KeyRef is where a KindGitHubApp's private key is, as a secret reference.
	KeyRef string

	// TokenRef is where a KindGitHubToken's token is, as a secret reference.
	TokenRef string

	// Pasted is set on a KindGitHubUser connection when the person pasted the stored token, so
	// the app's OAuth flow never issued it. Disconnect then deletes the token without revoking
	// it, since GitHub refuses to revoke a token through an app that didn't issue it.
	// SavePastedToken sets it and SaveUserToken clears it.
	Pasted bool

	Status Status

	// LastError is the last failure's message, with no secret in it. It is empty when Status
	// is StatusOK.
	LastError string

	Created  time.Time
	LastUsed time.Time
}

Connection is the record of one sign-in. Which fields apply depends on Kind, and Validate checks them.

func (Connection) Validate

func (c Connection) Validate() error

Validate checks that c's fields fit its Kind and Scope, and that every secret field is a secret reference rather than a secret. It never resolves a reference, so it works without the secret present, and its errors never repeat a field's value. Every failure wraps ErrInvalid.

type Kind

type Kind string

Kind says how a connection signs in.

const (
	// KindGitHubApp signs in as a GitHub App installation. The server mints a JWT from the
	// App's private key (KeyRef) and trades it for an hour-long installation token.
	KindGitHubApp Kind = "github-app"

	// KindGitHubToken signs in with a fixed token, such as a personal access token, read from
	// TokenRef.
	KindGitHubToken Kind = "github-token"

	// KindGitHubUser signs in as a person who connected their own GitHub account through OAuth.
	// The token is sealed in oneauth's user-token store under UserTokenProvider(ID) and the
	// person's subject, and refreshed there.
	KindGitHubUser Kind = "github-user"
)

type Option

type Option func(*Service)

Option configures a Service.

func WithAccessTTL

func WithAccessTTL(d time.Duration) Option

WithAccessTTL sets how long CanRead keeps an answer. Zero or less means DefaultAccessTTL.

func WithClock

func WithClock(now func() time.Time) Option

WithClock sets the service's clock, which stamps LastUsed. Tests use it.

func WithHTTPClient

func WithHTTPClient(c *http.Client) Option

WithHTTPClient sets the client for calls to GitHub: installation tokens, refreshes and revokes. Nil means http.DefaultClient.

func WithReadCheck

func WithReadCheck(f ReadCheck) Option

WithReadCheck sets how CanRead asks a service whether a connection can read a source. Without it, CanRead returns ErrNotConfigured.

func WithUserTokens

func WithUserTokens(store outbound.UserTokenStore, masterKeyRef string, oauth *oauth2.Config) Option

WithUserTokens lets the service hold people's own tokens. store keeps them sealed with a key derived from the master key, which masterKeyRef names as a secret reference to 64 hex characters ("env:NAME" or "file:/abs/path"). oauth is the OAuth app's config, which refreshes a token and whose client ID and secret revoke one.

type ReadCheck

type ReadCheck func(ctx context.Context, baseURL, source string, ts oauth2.TokenSource) (bool, error)

ReadCheck asks a service whether ts can read source, using the API at baseURL. It returns false with a nil error for a definite no, such as GitHub's 404 for a private repo, and also when baseURL isn't the host it serves. Any other failure is an error. The GitHub driver's CanRead method is one.

type Scope

type Scope string

Scope says whose sign-in a connection is.

const (
	// ScopeServer signs in as the server. Anyone the app lets read a mount reads it through the
	// connection, so the app's own sharing rules decide who sees what.
	ScopeServer Scope = "server"

	// ScopePerson signs in for Owner alone. Only a request whose viewer is Owner gets a token,
	// so GitHub decides what that person can read.
	ScopePerson Scope = "person"
)

type Service

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

Service hands out token sources for connections, and connects and disconnects people. It reads records from a Store and builds each connection's token source from oneauth's outbound package:

  • KindGitHubApp: one outbound.GitHubAppInstallation per connection, kept while the record is unchanged, so every mount on the connection shares its cached installation token.
  • KindGitHubToken: outbound.NewStatic over TokenRef.
  • KindGitHubUser: oneauth's outbound.UserTokens under UserTokenProvider(ID) and the owner's subject. It needs WithUserTokens.

A Service is safe for concurrent use. Several processes can share one Store and one user-token store, since oneauth refreshes a person's token with compare-and-swap.

func NewService

func NewService(store Store, opts ...Option) *Service

NewService returns a service over store. Without WithUserTokens, a KindGitHubUser connection returns ErrNotConfigured.

func (*Service) CanRead

func (s *Service) CanRead(ctx context.Context, source string) (string, error)

CanRead returns the ID of a connection of the viewer's that can read source, such as "github://acme/board". An app calls it to decide whether to show a person something it linked from a private repo, as agni#1728 does.

It tries the viewer's own connections in ID order, each with its token source, and returns the first one the read check says can read. A request with no viewer returns ErrNotOwner. When none can, or the viewer has no connection, it returns ErrNoAccess. When a check failed and none succeeded, it returns that failure instead of ErrNoAccess, since the answer isn't known.

A yes or a no is kept for the access TTL per viewer and source, so a page that checks many links asks GitHub once per repo. A failure isn't kept. SaveUserToken, SavePastedToken and Disconnect forget the owner's kept answers, and so does ForgetAccess. Server connections are never tried, since they would answer for the server rather than the person.

func (*Service) Disconnect

func (s *Service) Disconnect(ctx context.Context, id string) error

Disconnect removes connection id. For a KindGitHubUser connection it first revokes the token at GitHub and deletes it from the user-token store, through oneauth's UserTokens.Revoke. When the revoke fails it returns the error and keeps both the token and the record, so the app can retry. When the record's Pasted is set, it deletes the token with no call to GitHub, since the app didn't issue it and can't revoke it. Other kinds have nothing to revoke here: an App installation is removed on GitHub, and a fixed token by whoever issued it. A missing connection is not an error. Once the record is gone, CanRead forgets the owner's kept answers.

func (*Service) ForgetAccess added in v0.7.20

func (s *Service) ForgetAccess(viewer string)

ForgetAccess drops every answer CanRead keeps for viewer, so the next call asks the service again. The service forgets on its own when SaveUserToken, SavePastedToken or Disconnect changes a person's connection. An app that adds, changes or removes a person's connection through the Store calls ForgetAccess after the write, or the person waits out the access TTL. A CanRead already running for viewer still returns its answer, but doesn't keep it.

func (*Service) SavePastedToken added in v0.7.17

func (s *Service) SavePastedToken(ctx context.Context, id string, tok *oauth2.Token) error

SavePastedToken keeps tok as the token of KindGitHubUser connection id, as SaveUserToken does, for a token the person pasted rather than one the app's OAuth flow issued. It sets the record's Pasted, so Disconnect deletes the token without asking GitHub to revoke it. GitHub refuses that revoke for a token the app didn't issue. A later SaveUserToken clears Pasted.

func (*Service) SaveUserToken

func (s *Service) SaveUserToken(ctx context.Context, id string, tok *oauth2.Token) error

SaveUserToken keeps tok as the token of KindGitHubUser connection id, sealed, and sets the record's status back to StatusOK. The app calls it from its OAuth callback after a person connects, with the viewer set as for TokenSource. The token must come from the app's own OAuth flow, since Disconnect revokes it through the app. A pasted token goes through SavePastedToken. Once the token is saved, CanRead forgets the owner's kept answers, so a no from before the person connected doesn't outlive the connection.

func (*Service) TokenSource

func (s *Service) TokenSource(ctx context.Context, id string) (oauth2.TokenSource, error)

TokenSource returns the token source for connection id. A mounts driver wraps it in an oauth2.Transport. Its signature fits the mounts registry's WithCredentials option.

A ScopePerson connection gives a source only when Viewer(ctx) is its Owner, and returns ErrNotOwner otherwise, a request with no viewer included. A missing connection returns ErrNotFound. A user connection without WithUserTokens returns ErrNotConfigured.

The returned source's Token returns ErrReconnect, wrapping outbound.ErrReconnect, when a person's token can't be refreshed, and sets the record's Status to StatusReconnect. Any other failure sets StatusFailed. LastError gets the message, which never holds a token. The next token that works sets Status back to StatusOK.

TokenSource also stamps the record's LastUsed, at most once per LastUsedEvery.

type Status

type Status string

Status records the last thing the server learned about a connection's sign-in.

const (
	// StatusOK means the last token request worked, or none has been made.
	StatusOK Status = "ok"

	// StatusReconnect means the person's token can't be refreshed, so they have to connect
	// again. It follows oneauth's outbound.ErrReconnect.
	StatusReconnect Status = "reconnect"

	// StatusFailed means the last token request failed for another reason, in LastError.
	StatusFailed Status = "failed"
)

type Store

type Store interface {
	// GetConnection returns the record with that ID, or ErrNotFound.
	GetConnection(ctx context.Context, id string) (Connection, error)

	// ListConnections returns the connections owned by owner, in ID order. An empty owner lists
	// the ScopeServer ones.
	ListConnections(ctx context.Context, owner string) ([]Connection, error)

	// PutConnection creates c, or replaces the record with c.ID. It calls Validate first.
	PutConnection(ctx context.Context, c Connection) error

	// DeleteConnection removes the record with that ID. Deleting a missing record is not an
	// error. Revoking a person's token and deleting it from the user-token store is the
	// caller's job, before this.
	DeleteConnection(ctx context.Context, id string) error
}

Store keeps connection records. Several processes may share one.

Directories

Path Synopsis
Package connectionstest is the contract suite for connections.Store.
Package connectionstest is the contract suite for connections.Store.
Package fsstore keeps connection records in a folder, one YAML file per connection named <id>.yaml.
Package fsstore keeps connection records in a folder, one YAML file per connection named <id>.yaml.

Jump to

Keyboard shortcuts

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