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 ¶
- Variables
- func ExitCode(err error) int
- func Main(cfg Config)
- func ReadValue(stdin io.Reader, value string) ([]byte, error)
- func Run(ctx context.Context, cfg Config, args []string) error
- func Version() semver.Version
- type Auth
- type Config
- type Credential
- type Refresher
- type Response
- type SelfAuthenticator
- type StatusError
- type Transport
- type TransportError
- type UsageError
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 SelfAuthenticator ¶
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 ¶
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 ¶
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
Source Files
¶
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. |