tokens

package
v0.1.3 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 16 Imported by: 0 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 tokens renders, reads back and removes the credentials that package managers and VCS clients read from their own files: Composer's auth.json, .npmrc, Docker's config.json, git's credential store and .netrc.

It is the Go port of simtabi/auth-token-manager (see CHANGELOG for the exact revision). The package is pure: it turns config and file text into file text, and never touches the filesystem or the environment itself; the services layer (internal/services/tokensvc) does the I/O, sandboxing and permission hardening. The output of every renderer, merge, scanner and purge is byte-compatible with the Python tool, which golden tests pin.

Index

Constants

View Source
const (
	AliasBegin = "# >>> authama token aliases >>>"
	AliasEnd   = "# <<< authama token aliases <<<"
)

The markers around the managed block.

View Source
const (
	Composer = "composer"
	NPM      = "npm"
	Docker   = "docker"
	Git      = "git"
	Netrc    = "netrc"
)

The five targets, in their documented order.

View Source
const (
	KindToken   = "token"
	KindBasic   = "basic"
	KindPair    = "pair"
	KindHeaders = "headers"
)

The four credential kinds.

View Source
const (
	ShellPOSIX      = "posix"
	ShellFish       = "fish"
	ShellPowerShell = "powershell"
	ShellCmd        = "cmd"
)

Shell families for EnvExport.

View Source
const Mask = "********"

Mask stands in for a secret anywhere one is shown without being revealed.

View Source
const StarterHelp = "Token config — maps each host to how its credential is built from the " +
	"environment, grouped by TARGET tool. Stores ENV VAR NAMES, not secrets. " +
	"See `authama token examples` for a reference and `authama token providers` for " +
	"Composer services. Delete the hosts you don't use."

StarterHelp heads a config scaffolded for chosen targets.

Variables

View Source
var ErrUnreadableJSON = errors.New("is not a JSON object; fix or move it, then retry (refusing to replace it)")

ErrUnreadableJSON means an existing auth.json or docker config.json is not a JSON object. The Python tool replaced such a file with a warning; this port refuses, because the file may be a half-written edit that still holds credentials and replacing it would lose them.

View Source
var PathOverrideVars = []string{"COMPOSER_HOME", "NPM_CONFIG_USERCONFIG", "DOCKER_CONFIG", "NETRC", "XDG_CONFIG_HOME", "APPDATA"}

PathOverrideVars are the variables the native tools read to relocate their files. In dev mode the services layer hides them, so a sandboxed run can never be redirected onto a real file.

Functions

func AliasBlock

func AliasBlock(as []Alias, command string) string

AliasBlock is the marked block for a startup file.

func AliasLines

func AliasLines(as []Alias) []string

AliasLines renders `alias name='value'` lines, for eval or a block.

func AllTargetsTemplate

func AllTargetsTemplate() string

AllTargetsTemplate is the shipped all-targets example, byte for byte.

func BlockAliasLines

func BlockAliasLines(text string) []string

BlockAliasLines are the alias lines inside the managed block.

func CanonicalHost

func CanonicalHost(target, host string) string

CanonicalHost is the host key Scan reports for a user-typed host: git accepts a bare host, a full URL or a trailing slash.

func Check

func Check(c Credential) error

Check reports why c cannot be written safely, or nil.

func DefaultProfile

func DefaultProfile(home, shell string, login bool, exists func(string) bool) string

DefaultProfile is the startup file for the shell named by $SHELL: the rc file, or with login the login profile.

func Describe

func Describe(target, host string) string

Describe is a short human summary: the provider, if known, and what the credential is for, e.g. "GitHub · Git over HTTPS".

func DetectShell

func DetectShell(getenv func(string) string, windows bool) string

DetectShell guesses the current shell family from the environment the way the Python tool did: PowerShell on Windows when PSModulePath is set, fish or POSIX from $SHELL, else cmd/PowerShell on Windows and POSIX elsewhere.

func DockerDelegation

func DockerDelegation(text string) (store string, helpers map[string]string)

DockerDelegation reads credsStore and credHelpers from a docker config; both are empty when the text is not a JSON object.

func EnvExport

func EnvExport(name, value, shell string) string

EnvExport renders one NAME=value assignment for a shell family.

func ExpandEnv

func ExpandEnv(text string, get Lookup) (string, bool)

ExpandEnv substitutes ${VAR}; ok is false if a referenced var is absent (a var that is set but empty substitutes as empty).

func GitKey

func GitKey(value string) string

GitKey is the canonical key of a git credential line or a bare host: the lower-cased hostname, an explicit port, and any path, without scheme, credentials or trailing slash, so "dev.azure.com/org" and "git.acme:8443" round-trip for listing and removal.

func HasAliasBlock

func HasAliasBlock(text string) bool

HasAliasBlock reports whether text holds a managed block.

func HasLegacyAliasBlock

func HasLegacyAliasBlock(text string) bool

HasLegacyAliasBlock reports whether text holds an auth-token-manager block.

func IsTarget

func IsTarget(t string) bool

IsTarget reports whether t is one of the five targets.

func IsTokenMechanism

func IsTokenMechanism(m string) bool

IsTokenMechanism reports whether a Composer mechanism stores one token.

func LoadCatalogServices

func LoadCatalogServices() map[string]string

LoadCatalogServices is the Composer service -> mechanism map.

func Mechanism

func Mechanism(s Spec) string

Mechanism is the Composer mechanism for a spec: an explicit type wins, else the service alias maps to one.

func Mechanisms

func Mechanisms() []string

Mechanisms lists every Composer mechanism (auth.json section) the catalog knows, sorted.

func ParseEnvFile

func ParseEnvFile(text string) [][2]string

ParseEnvFile reads VAR=value lines, as --source did: blank lines and comments are skipped and one layer of quotes is stripped.

func Purge

func Purge(target, host, text string) string

Purge removes host from one target's file content. The caller checks the host is present first (Scan) and appends the final newline.

func RelevantWarnings

func RelevantWarnings(warnings []string, selected map[string]bool) []string

RelevantWarnings filters resolution warnings to the selected targets (all when none are selected) and, past six "env var not set" skips, folds those into one summary line at the end, as the Python tool did: a starter config lists dozens of example hosts and a wall of identical lines hides the mistakes that matter.

func RenderAliasInstall

func RenderAliasInstall(text, block string) string

RenderAliasInstall is text with the block appended, replacing any old one.

func RenderAliasRemove

func RenderAliasRemove(text string) string

RenderAliasRemove is text without the block.

func StripAliasBlock

func StripAliasBlock(text string) string

StripAliasBlock removes the managed block (and the legacy one), with the blank lines just before it. Line-based, so hand edits inside survive.

func Targets

func Targets() []string

Targets lists the five targets in order.

func UseCatalog

func UseCatalog(text string) error

UseCatalog replaces the embedded catalog with text, a catalog.json the user supplied (auth-token-manager read one from $AUTH_TOKEN_MANAGER_CATALOG), so a new Composer service or provider can be added without a new build. Empty text restores the embedded catalog. A catalog that does not parse, or names a target this package cannot write, is refused and the current one is kept.

func ValidateEntry

func ValidateEntry(sp Spec) string

ValidateEntry reports the fields a spec is missing for its target, or "".

Types

type Alias

type Alias struct{ Name, Value string }

Alias is one managed alias.

func DefaultAliases

func DefaultAliases(command string) []Alias

DefaultAliases are the managed aliases for command (the binary name).

type Catalog

type Catalog struct {
	Targets         []string
	Menu            []MenuItem
	TargetFields    map[string]map[string][]string
	TokenMechanisms map[string]bool // Composer mechanisms that store one token
	Services        map[string]string

	Enterprise map[string]EnterpriseHost

	Providers map[string][]Provider

	DefaultConfig string // the built-in minimal config, as JSON text
	// contains filtered or unexported fields
}

Catalog is the data the Python tool kept in config/catalog.json: targets, Composer services, enterprise hosts, providers and required config fields. Adding a service or provider is an edit to catalog.json, not to code.

func LoadCatalog

func LoadCatalog() (*Catalog, error)

LoadCatalog returns the catalog in use: one installed by UseCatalog, or the embedded one (a test pins that the embedded one always reads).

func (*Catalog) EnterpriseNames

func (c *Catalog) EnterpriseNames() []string

EnterpriseNames lists the services that can be cloud or self-hosted.

func (*Catalog) ProviderTargets

func (c *Catalog) ProviderTargets() []string

ProviderTargets lists the targets with an interactive provider list.

func (*Catalog) ServiceNames

func (c *Catalog) ServiceNames() []string

ServiceNames lists the Composer service aliases in catalog order.

type Config

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

Config is a parsed token config, in file order.

func NewConfig

func NewConfig() *Config

NewConfig is an empty config.

func ParseConfig

func ParseConfig(text string) (*Config, error)

ParseConfig reads a token config; it must be a JSON object.

func StarterConfig

func StarterConfig(targets []string) (*Config, error)

StarterConfig assembles a config from the per-target templates.

func TargetTemplate

func TargetTemplate(target string) (*Config, error)

TargetTemplate is the starter template for one target.

func (*Config) JSON

func (c *Config) JSON() string

JSON renders the config as json.dumps(indent=2) did.

func (*Config) Resolve

func (c *Config) Resolve(get Lookup) *Set

Resolve builds a credential set from the config's references, reading the secrets through get. Entries that cannot be built are skipped, and why is recorded in the set's Warnings.

func (*Config) SetEntry

func (c *Config) SetEntry(target, host string, fields [][2]string)

SetEntry adds or replaces one host's reference entry in the v2 shape, keeping the rest of the file in order. fields is ordered key/value pairs.

func (*Config) Setting

func (c *Config) Setting(name string) string

Setting reads a string from the optional "_settings" object.

func (*Config) Specs

func (c *Config) Specs() []Spec

Specs lists every entry, normalised to v2, in target then file order.

type Credential

type Credential struct {
	Target     string
	Host       string
	Kind       string
	Mechanism  string // composer only: the auth.json section
	Token      string
	Username   string
	Password   string
	Key        string
	Secret     string
	Headers    []string
	Scope      string // npm only: the @org bound to this registry
	AlwaysAuth bool   // npm only
}

Credential is one fully resolved entry; its secrets are already read.

type EnterpriseHost

type EnterpriseHost struct {
	Cloud   string // "" when self-hosted by nature
	Domains string // "" when Composer needs no *-domains entry
}

EnterpriseHost says whether a Composer service has a public cloud host and which composer.json config key lists its self-hosted domains.

type Host

type Host struct {
	Home    string
	Getenv  func(string) string
	Windows bool
	MacOS   bool
	Exists  func(string) bool // any file or directory
	IsDir   func(string) bool
}

Host describes the machine the target files live on. The services layer fills it from the real OS, or from a sandbox in dev mode; this package never reads the environment or the filesystem itself.

func (Host) ComposerHome

func (h Host) ComposerHome() string

ComposerHome resolves Composer's home the way Composer does.

func (Host) TargetPath

func (h Host) TargetPath(target, project string) string

TargetPath is where a target's file lives, found the way the native tool finds it, honouring its own env overrides. project scopes composer and npm to a project directory; docker, git and netrc are always per-user.

type Installed

type Installed struct {
	Target        string `json:"target"`
	Host          string `json:"host"`
	Kind          string `json:"kind"` // the composer section, or token / basic
	Username      string `json:"username"`
	SecretPresent bool   `json:"secret_present"`
	Secret        string `json:"secret"`
	Description   string `json:"description"`
	File          string `json:"file"`
}

Installed is one credential found in an auth file on disk. Secret is the value itself and is only filled in when a caller asks to reveal it.

func Scan

func Scan(target, text string) []Installed

Scan reads the credentials out of one target's file content. It never fails: content it cannot parse holds no credentials it can list.

type Lookup

type Lookup func(string) (string, bool)

Lookup reads an environment variable, reporting whether it is set.

type MenuItem struct {
	Key   string `json:"key"`
	Label string `json:"label"`
}

MenuItem is one entry of the "which tool?" menu.

type Provider

type Provider struct {
	Key      string `json:"key"`
	Label    string `json:"label"`
	Cloud    string `json:"cloud"`
	Hostable bool   `json:"hostable"`
}

Provider is one row of the interactive provider picker for a target.

type Set

type Set struct {
	Warnings []string
	// contains filtered or unexported fields
}

Set is an ordered collection of credentials, at most one per (target, host): adding a host again replaces it and moves it to the end. An entry whose secret is empty is dropped, never stored half-built.

func NewSet

func NewSet() *Set

NewSet returns an empty set.

func Template

func Template() *Set

Template is the complete reference skeleton: every target and mechanism, with placeholders that are never valid credentials.

func (*Set) Add

func (s *Set) Add(c Credential) bool

Add stores c if its required secrets are present; trailing whitespace a secret manager left on a value is trimmed first. It reports whether c was kept.

func (*Set) Apply

func (s *Set) Apply(target, mechanism, host string, c Credential) bool

Apply adds one interactively entered credential: token mechanisms use token (+ scope for npm); basic ones username + password; bitbucket key + secret; custom-headers headers. It reports whether it was kept.

func (*Set) ComposerEnv

func (s *Set) ComposerEnv(shell string) string

ComposerEnv is the COMPOSER_AUTH export line for the given shell family.

func (*Set) ComposerJSON

func (s *Set) ComposerJSON() string

ComposerJSON is the composer entries as a fresh auth.json document.

func (*Set) DockerJSON

func (s *Set) DockerJSON() string

DockerJSON is the docker entries as a fresh config.json document.

func (*Set) Entries

func (s *Set) Entries(target string) []Credential

Entries returns the credentials for target, or all of them for "".

func (*Set) GitCredentials

func (s *Set) GitCredentials() string

GitCredentials renders the git entries as credential-store lines.

func (*Set) Len

func (s *Set) Len(target string) int

Len counts the credentials for target, or all of them for "".

func (*Set) NPMRC

func (s *Set) NPMRC() string

NPMRC renders the npm entries as .npmrc lines.

func (*Set) NetrcText

func (s *Set) NetrcText() string

NetrcText renders the netrc entries, one machine per line.

func (*Set) RedactedJSON

func (s *Set) RedactedJSON(only map[string]bool) string

RedactedJSON dumps the entries, secrets masked, for review; only lets limit it to some targets (nil for all).

func (*Set) Remove

func (s *Set) Remove(target, host string) bool

Remove drops the credential for (target, host) and reports whether one was.

func (*Set) Render

func (s *Set) Render(target string, existing string, present bool) (string, error)

Render merges the set's entries for target into existing, the current file content (absent = render fresh). The result has no trailing newline; the writer adds one.

func (*Set) Targets

func (s *Set) Targets() []string

Targets lists the targets that have at least one credential, in order.

type Spec

type Spec struct {
	Target     string
	Host       string
	Type       string
	Service    string
	Env        string
	UserEnv    string
	PassEnv    string
	KeyEnv     string
	SecretEnv  string
	Headers    []string
	Scope      string
	AlwaysAuth bool
	// contains filtered or unexported fields
}

Spec is one host's entry, with the fields a config may set.

func (Spec) Has

func (s Spec) Has(field string) bool

Has reports whether the entry set a field at all.

Jump to

Keyboard shortcuts

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