earl

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Sep 10, 2026 License: MIT Imports: 21 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.

README

earl

earl is a command-line client for a JSON HTTP API. The verb and path you would send are what you type:

earl get /session
earl post /accounts -d '{"email":"t@x.com","secret":"hunter2hunter2"}'
earl patch /games/1 -d @game.json
earl put /me/password -d @- < body.json

It exists because curl does not know your API's auth model. Everything earl adds over curl is that knowledge: it signs in, saves the credential, attaches it to every request, renews it when the server rejects it, and forgets it on sign-out.

Because it is a passthrough, it covers the whole API without per-endpoint code and stays correct as endpoints are added. It opens no database, imports no store, and knows no domain rules — which is what lets it be used as a test harness. A client that reimplements the server's rules stops being evidence that the server implements them.

SPEC.md is normative.

Using it

earl is a library plus a per-application main. The library owns the command tree, transport, output, argument handling, and credential store; the application supplies its defaults and one Auth:

package main

import (
	"github.com/maloquacious/earl"
	"github.com/maloquacious/earl/auth"
)

func main() {
	earl.Main(earl.Config{
		Program:    "earl",
		Version:    version.String(),
		EnvPrefix:  "EARL",
		BaseURL:    "http://localhost:8080/api",
		WhoamiPath: "/me",
		Env:        env, // resolved and validated before this call
		Auth: auth.NewBearer(auth.Bearer{
			LoginPath:  "/auth/login",
			LogoutPath: "/auth/logout",
			Fields: auth.Fields{
				Identity: "email", Secret: "secret",
				Token: "token", Expires: "expiresAt",
			},
		}),
	})
}

That is the entire integration. There is no stock binary: what differs per API is the login exchange, and making it a compile-time seam means a mismatch is a build failure rather than a runtime message.

Commands

Command
get, post, put, patch, delete one positional PATH, -d body, -H headers, --no-auth
login authenticate and save the credential
logout revoke it and forget it
whoami get <WhoamiPath>, and nothing else
identities what is saved for this base URL
version the build version

Bodies and secrets resolve the same three ways: inline, @file, or @- for stdin. The sigil is required — a mistyped path is an error, not a literal body.

Auth schemes

auth.NewBearer for a token in a header, with optional renewal on 401. auth.NewCookie for a session cookie captured from Set-Cookie at login. Anything else implements earl.Auth directly; nothing in auth is privileged.

Behaviour worth knowing

  • stdout is the response. A 2xx writes the body there and nothing else. Everything earl says about itself goes to stderr, so earl get /x | jq works.
  • Indented for a terminal, raw for a pipe. Non-JSON passes through either way.
  • Exit codes: 0 2xx · 1 usage or local error · 2 no answer · 3 an answer that was not 2xx. A runner that exits 0 on a 500 cannot fail a build.
  • Redirects are not followed. A 302 is reported, not chased.
  • A credential is never printed. Not at any verbosity. There is a test whose only job is to keep that true.
  • Credentials live in $XDG_CONFIG_HOME/<StateDir>/<Env>/credentials.json, mode 0600, keyed by base URL and identity so one file can hold several accounts. <Env> keeps development and production from ever sharing one.

Development

go test ./...          # includes the SPEC §13 conformance tests
go test -race ./...

appendix_test.go drives the three implementations catalogued in others.md — ecv4, ecv6, ecv8 — end to end as Config values, which is what keeps SPEC Appendix A.1 honest.

Documentation

Overview

Package earl is a command-line client for a JSON HTTP API. The verb and path you would send are what you type:

earl get /session
earl post /accounts -d '{"email":"t@x.com","secret":"hunter2hunter2"}'
earl patch /games/1 -d @game.json
earl put /me/password -d @- < body.json

It exists because curl does not know your API's auth model. Everything earl adds over curl is that knowledge: it signs in, saves the credential, attaches it to every request, renews it when the server rejects it, and forgets it on sign-out.

Because it is a passthrough it covers the whole API without per-endpoint code and stays correct as endpoints are added. This package opens no database, imports no store, and knows no domain rules; anything it appears to know about an application is the shape of a JSON body passing through.

An application supplies its defaults and one Auth implementation:

func main() {
	earl.Main(earl.Config{
		Program:    "earl",
		Version:    version.String(),
		EnvPrefix:  "EARL",
		BaseURL:    "http://localhost:8080/api",
		WhoamiPath: "/me",
		Env:        env,
		Auth: auth.NewBearer(auth.Bearer{
			LoginPath:  "/auth/login",
			LogoutPath: "/auth/logout",
			Fields: auth.Fields{
				Identity: "email", Secret: "secret",
				Token: "token", Expires: "expiresAt",
			},
		}),
	})
}

SPEC.md is normative; doc comments cite its sections.

Index

Constants

This section is empty.

Variables

View Source
var ErrNoRenewal = errors.New("no renewal mechanism configured")

ErrNoRenewal reports that an Auth cannot renew a credential. earl treats it as "nothing to try" rather than as a renewal failure, so a 401 is reported as itself instead of behind a misleading diagnostic.

Functions

func ExitCode

func ExitCode(err error) int

ExitCode maps an error to the process exit code required by SPEC §8.4:

0  success
1  usage, configuration, or local error
2  transport failure - the request did not get an answer
3  the request got an answer and it was not 2xx

func Main

func Main(cfg Config)

Main runs one command line and exits with the code from SPEC §8.4.

func ReadValue

func ReadValue(stdin io.Reader, value string) ([]byte, error)

ReadValue resolves an indirect flag value into bytes (SPEC §7.4):

""       no value
@-       read stdin
@name    read the file name
other    the literal bytes

The sigil is required. Auto-detecting a file by stat, as ecv4 did, sends a mistyped path to the server as a literal body and answers with a confusing 4xx; a missing @file is an error here instead.

The indirection matters for a secret as much as for a body: @- keeps it out of the command line, where anyone who can list processes would see it, and out of the shell history.

func Run

func Run(ctx context.Context, cfg Config, args []string) error

Run executes one command line and returns its error, after rendering it to cfg.Stderr. It never calls os.Exit, so tests can call it directly.

func Version

func Version() semver.Version

Version reports this module's version.

Build carries the commit the binary was built from, read from the build information the Go toolchain embeds, so it is present in an installed binary and empty under `go run` or `go test`.

An application wires it into its own Config, where it names the binary in the User-Agent and answers the version command:

earl.Main(earl.Config{Version: earl.Version().String(), ...})

Types

type Auth

type Auth interface {
	// Attach adds cred to req. A zero Credential must leave req unchanged, so
	// that an anonymous request is sent as-is and the server decides.
	Attach(req *http.Request, cred Credential)

	// Login exchanges an identity and a secret for the credential to save.
	Login(ctx context.Context, tr Transport, identity, secret string) (Credential, error)

	// Logout revokes cred on the server. An error does not prevent earl from
	// dropping the local copy: a credential the server has forgotten is not
	// one worth keeping, and leaving it produces confusing 401s later.
	Logout(ctx context.Context, tr Transport, cred Credential) error
}

Auth supplies the parts of authentication that differ between APIs: how a credential is obtained, how it is attached to a request, and how it is revoked. It is the only thing an application must implement or configure (SPEC §9.1).

type Config

type Config struct {
	// Program is the binary's name, used in usage text and diagnostics and as
	// the default StateDir. Required.
	Program string

	// Version is printed by the version command. When empty, no version
	// command is registered.
	Version string

	// EnvPrefix prefixes every environment variable earl reads, so --base-url
	// is fed by <EnvPrefix>_BASE_URL. Required.
	//
	// It should not be the server's own prefix: pointing a client at another
	// host must not mean editing, or risk disturbing, the variables a server
	// reads. It should be shared between sibling clients meant to share a
	// credential file, because credentials are keyed by base URL - two clients
	// reading two different variables can be pointed at two different servers,
	// and the shared file would quietly stop being shared.
	EnvPrefix string

	// StateDir is the directory name under the user config root. Defaults to
	// Program. It names the project, not a command, when several commands
	// share one credential file.
	StateDir string

	// BaseURL is the default for --base-url. Required.
	BaseURL string

	// APIPath is appended to a --base-url carrying no path, so that
	// https://host and https://host/api/v1 address the same endpoint.
	APIPath string

	// IdentityName names the flag and environment variable that select a saved
	// identity: "email" gives --email and <EnvPrefix>_EMAIL. Defaults to
	// "email".
	IdentityName string

	// WhoamiPath is the path the whoami command requests. When empty, no
	// whoami command is registered.
	WhoamiPath string

	// Auth obtains, attaches, and revokes the credential. Required.
	Auth Auth

	// ReloginOnExpiry allows a full re-login, using the configured identity and
	// secret, when a 401 cannot be resolved by renewal. Off by default: it
	// requires a usable secret in the environment of every invocation, which is
	// a choice an application makes deliberately.
	ReloginOnExpiry bool

	// Env scopes the credential file and is resolved by the application before
	// flags are parsed. Required, and required to be validated against a closed
	// set by the application - that validation is what lets earl use it as a
	// path segment without further checking.
	Env string

	// Extra registers application subcommands (SPEC §11). It is for operations
	// that are not a request an operator can type; a typed wrapper around an
	// endpoint a verb could already reach does not belong here.
	Extra []*ff.Command

	// Stdin, Stdout, and Stderr default to the process's own. They are
	// injectable so tests can drive and capture a whole run.
	Stdin          io.Reader
	Stdout, Stderr io.Writer
}

Config is everything earl needs that it cannot work out for itself.

type Credential

type Credential struct {
	Value     string            `json:"value"`
	Name      string            `json:"name,omitempty"`  // cookie name, when the scheme has one
	Renew     string            `json:"renew,omitempty"` // refresh token, when the scheme has one
	ExpiresAt time.Time         `json:"expires_at,omitzero"`
	Extra     map[string]string `json:"extra,omitempty"` // scheme-specific, opaque to earl
}

Credential is one saved authentication, whatever its scheme. Value is the live secret; everything else is metadata for attaching or renewing it.

The zero Credential means "no credential": a request carrying it is sent anonymously and the server decides (SPEC §10.3).

func (Credential) Expired

func (c Credential) Expired() bool

Expired reports whether c's recorded expiry has passed.

It is advisory. earl never refuses to send an expired credential: clocks disagree, and the server is the authority on whether a credential is still good (SPEC §9.2). It labels identities output and nothing else.

func (Credential) IsZero

func (c Credential) IsZero() bool

IsZero reports whether c holds no credential.

type Refresher

type Refresher interface {
	Refresh(ctx context.Context, tr Transport, cred Credential) (Credential, error)
}

Refresher is implemented by an Auth that can renew a credential without the secret. earl calls Refresh at most once per invocation.

type Response

type Response struct {
	Status  int
	Header  http.Header
	Cookies []*http.Cookie
	Body    []byte
}

Response is one answered request.

func (*Response) OK

func (r *Response) OK() bool

OK reports whether the status is 2xx.

type SelfAuthenticator

type SelfAuthenticator interface {
	SelfAuthenticating(path string) bool
}

SelfAuthenticator is implemented by an Auth whose own endpoints authenticate from the request body rather than from the attached credential. earl does not react to a 401 from such a path by renewing and retrying: the 401 means bad credentials, and retrying would be both pointless and misleading.

type StatusError

type StatusError struct {
	Method string
	Path   string
	Status int
	Body   []byte
}

StatusError is a request that was answered with a non-2xx status.

Body is carried raw rather than rendered, because whether it is indented depends on the stream it lands on (SPEC §8.3), which an error does not know.

func (*StatusError) Error

func (e *StatusError) Error() string

type Transport

type Transport interface {
	Do(ctx context.Context, method, path string, body []byte, cred Credential) (*Response, error)
}

Transport sends one request against the configured base URL. earl hands it to an Auth so that login and logout reach the server exactly as every other command does - same base URL, timeout, redirect policy, limit, and User-Agent - without an Auth building a client of its own.

type TransportError

type TransportError struct {
	Method string
	Path   string
	Err    error
}

TransportError is a request that got no answer at all.

func (*TransportError) Error

func (e *TransportError) Error() string

func (*TransportError) Unwrap

func (e *TransportError) Unwrap() error

type UsageError

type UsageError struct{ Err error }

UsageError is a command line earl could not act on.

func (*UsageError) Error

func (e *UsageError) Error() string

func (*UsageError) Unwrap

func (e *UsageError) Unwrap() error

Directories

Path Synopsis
Package auth carries the credential schemes earl ships with: Bearer, for an API that authenticates with a token in a header, and Cookie, for one that authenticates with a session cookie.
Package auth carries the credential schemes earl ships with: Bearer, for an API that authenticates with a token in a header, and Cookie, for one that authenticates with a session cookie.

Jump to

Keyboard shortcuts

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