Skip to content
Source on GitHub (opens in a new tab)
import "github.com/barevoidco/zelk/core/secret"

Package secret keeps credential documents: a sign-in, OAuth tokens, a pairing key, provider keys. Each is a JSON document at a file path, kept either in that file, readable only by its owner, or in a Vault such as the operating system’s keychain, with a marker in the file naming the item. A lock other processes respect keeps two refreshes of a rotating token from overlapping, and every vault step is written down first so a crash at any point is settled by the next access.

Hosts supply the Vault; core has none of its own. docs/design/keychain.md is the design.

var (
// ErrUnavailable: no vault can be reached (no keychain service, or
// none configured).
ErrUnavailable = errors.New("keychain unavailable")
// ErrLocked: the keychain is locked, and the call may not ask the
// user to unlock it (see WithInteractive).
ErrLocked = errors.New("keychain locked")
// ErrDenied: the user, the keychain's access list or its provider
// refused.
ErrDenied = errors.New("keychain access denied")
// ErrMissingItem: the item a marker names isn't there, or holds no
// usable document.
ErrMissingItem = errors.New("keychain item missing")
// ErrUncertain: zelk can't know whether a call took effect. The
// document's intent settles it on the next access; callers must not
// act as if the write failed (revoke a token, say) and may try again.
ErrUncertain = errors.New("keychain outcome unknown")
// ErrCorrupt: two items share an identity, or a marker or intent
// can't be read.
ErrCorrupt = errors.New("credential storage corrupt")
// ErrInVault: the document is kept in a vault this Document wasn't
// given. The error names the vault's backend.
ErrInVault = errors.New("credentials are kept in a keychain")
// ErrNotInVault: a vault is required (WithRequireVault), and the
// document is still in a plain file.
ErrNotInVault = errors.New("credentials are in a plain file, and a keychain is required")
)

Errors a Vault or a Document returns. None of them ever means “no credentials”: a Document that can’t reach its item says why rather than reading as empty.

func Interactive(ctx context.Context) bool

Interactive reports whether ctx allows prompts (see WithInteractive).

func WithInteractive(ctx context.Context) context.Context

WithInteractive returns a context under which a vault may show the user a prompt: to unlock the keychain or to allow access. Without it a vault never starts any UI, and returns ErrLocked or ErrDenied instead. Hosts set it only where a person is attending and asked for the operation.

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

Document is one credential document (JSON) kept at a file path: in the file itself, readable only by its owner, or in a Vault item that a marker in the file names. The file at the path always decides which. Beside it sit a lock file (path + “.lock”) that other processes respect, and while a vault step is under way an intent file (path + “.intent”) that the next access uses to finish or undo it.

A Document is safe for concurrent use, also by other processes. It refuses directories owned by another user or writable by group or others, and symlinked document, lock, intent or staging paths. On Windows it judges ACLs instead of mode bits: the directory, and each file it opens, must be owned by the current user and open to no other principal but SYSTEM and Administrators. Where neither Unix ownership nor Windows ACLs exist, it fails closed.

The design, with every step and what a crash at each leaves, is docs/design/keychain.md.

func New(path string, opts ...Option) *Document

New returns the document at path. Its directory is created, private, on the first write. An existing directory is checked, never chmodded.

func (d *Document) Begin(ctx context.Context) (*Tx, error)

Begin takes the document’s exclusive lock, creating its directory if needed, and finishes any step a crashed process left. End releases it.

func (d *Document) Move(ctx context.Context, to Where) error

Move puts the document where to says: InVault copies it to a new item, checks the copy, and puts a marker over the file; InFile writes it over the marker and lets the item go. An absent document, or one already there, is left alone.

func (d *Document) Path() string

Path returns the document’s file path.

func (d *Document) Purge(ctx context.Context) error

Purge removes the document wherever it is kept, item included. The lock file stays. Signing out isn’t a purge: it is an Update that keeps what outlives a sign-out.

func (d *Document) Read(ctx context.Context) ([]byte, error)

Read returns the document, nil if there is none. It holds a shared lock while it reads the file and, for a marker, the vault item, so it never sees a marker whose item a concurrent move has just deleted.

func (d *Document) Update(ctx context.Context, fn func([]byte) ([]byte, error)) error

Update locks the document, gives fn what it holds (nil if nothing) and writes what fn returns in its place. When fn fails nothing is written and its error is returned.

func (d *Document) View(ctx context.Context, fn func([]byte) error) error

View calls fn with the document (nil if there is none) while holding a shared lock, so other files the same lock guards can be read in one consistent view with it. fn must not write them or begin a Tx on d.

type Option func(*Document)

Option configures a Document.

func WithLabel(label string) Option

WithLabel names the document’s vault items for people browsing the keychain, as in “zelk: ChatGPT sign-in”.

func WithNewIn(w Where) Option

WithNewIn says where a document is kept when it is first created: InFile (the default) or InVault, which needs WithVault. An existing document stays where it is until Move.

func WithRequireVault() Option

WithRequireVault refuses a document kept in a plain file (ErrNotInVault) and creates new documents in the vault: a managed policy’s requirement.

func WithVault(v Vault) Option

WithVault gives the Document the vault its marker may name. Without one a marker reads as ErrInVault, never as an empty document.

type Ref struct {
Backend string `json:"backend"`
ID string `json:"id"`
Location string `json:"location,omitempty"`
}

Ref names one item in a vault: which backend keeps it, its identity there, and the place (a keychain file, a collection) it was created in. Every operation on the item targets that place, so a changed default keychain or collection can’t send it elsewhere.

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

Tx is a Document held under its exclusive lock. Hosts use it to make one change span the document and other files guarded by the same lock.

func (t *Tx) End()

End releases the lock. It is safe to call more than once.

func (t *Tx) Read(ctx context.Context) ([]byte, error)

Read returns the document, nil if there is none.

func (t *Tx) Where(ctx context.Context) (Where, Ref, error)

Where reports where the document is kept, and its item’s Ref when that is a vault.

func (t *Tx) Write(ctx context.Context, data []byte) error

Write replaces the document with data, where the document is kept: in the file, or as a new vault item that a new marker names, the old item let go after. A new document goes where WithNewIn says.

type Vault interface {
// Backend names the vault's kind, as recorded in a Ref.
Backend() string
// NewRef returns a fresh Ref at the vault's default place. It creates
// nothing.
NewRef(ctx context.Context) (Ref, error)
// Get returns the item's data, or ErrMissingItem.
Get(ctx context.Context, r Ref) ([]byte, error)
// Create stores data as a new item. It never replaces an item: an
// existing one with r's identity is an error.
Create(ctx context.Context, r Ref, label string, data []byte) error
// Delete removes the item. A missing item isn't an error.
Delete(ctx context.Context, r Ref) error
}

Vault keeps whole documents as items, such as an operating system keychain. Items are never changed in place: a Document writes a new item and lets the old one go, so a Vault needs only to create, read and delete. Callers hold the document’s file lock around every call, so a Vault needs no locking of its own.

A Vault reports a call it couldn’t finish with one of this package’s errors. Once a call returns, its result stands even if ctx ended meanwhile: a Create that went through returns nil.

type Where int

Where says where a Document keeps its contents.

const (
// Absent means there is no document.
Absent Where = iota
// InFile means the document is the file itself.
InFile
// InVault means the file holds a marker naming a vault item.
InVault
)
func (w Where) String() string