auth

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 10, 2026 License: MIT Imports: 25 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 auth applies authentication to outgoing requests, driven by the `# @auth <type> [args]` directive or the `auth.default` setting in apic.yaml. Supported types: none, bearer, basic, apikey, digest, aws, oauth2, exec.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotInteractive = errors.New("oauth2: grant=authorization_code needs a browser sign-in and no cached token exists; run the request once interactively (apic run <id>) to sign in, and the token is cached and refreshed from then on")

ErrNotInteractive is returned when the grant needs a browser and no person is there to use one.

View Source
var Types = map[string]string{
	"none":   "send no credentials (overrides a project default)",
	"bearer": "bearer <token>: Authorization: Bearer <token>",
	"basic":  "basic <user> <password>: HTTP basic auth",
	"apikey": "apikey <key> [header=X-Api-Key] [query=name] [prefix=..]: send the key as a header (default X-Api-Key, no prefix) or a query parameter",
	"digest": "digest <user> <password>: HTTP digest auth (RFC 7616), answering the server's challenge",
	"aws":    "aws [service=execute-api] [region=..] [profile=..]: AWS Signature V4 using the SDK credential chain",
	"oauth2": "oauth2 tokenUrl=.. clientId=.. [clientSecret=..] [grant=client_credentials|password|device_code|authorization_code] [scope=..] [username=..] [password=..] [audience=..] [deviceUrl=..] [authUrl=..] [redirectPort=..] [redirectUrl=http://localhost:<port>/<path>] [clientAuth=body|basic]",
	"exec":   "exec <command> [args..] [header=Authorization] [prefix=Bearer] [ttl=10m]: use a command's stdout as the token (needs auth.allowExec in apic.yaml)",
}

Types lists the supported auth types with a one-line description.

Functions

func Apply

func Apply(ctx context.Context, s *Spec, req *http.Request, body []byte, env *Env) error

Apply adds credentials to req according to a rendered spec. body is the request body as sent (needed for AWS payload hashing).

func CacheKey

func CacheKey(s *Spec) string

CacheKey identifies the token cache entry for a rendered oauth2 spec.

func DescribeCached

func DescribeCached(raw string, now time.Time) string

DescribeCached renders a cached token entry for `apic session`.

func OpenBrowser

func OpenBrowser(u string) error

OpenBrowser asks the system to open a URL: xdg-open, open or rundll32. Failure is not fatal; the URL is always printed as well.

func SignSigV4

func SignSigV4(req *http.Request, body []byte, creds AWSCredentials, service, region string, at time.Time)

SignSigV4 signs req in place with AWS Signature Version 4 (header auth). body is the request body as sent. Behaviour matches the AWS SDK signer: the path is URI-encoded twice except for S3, query parameters are sorted, and Content-Length is signed when present.

Types

type AWSCredentials

type AWSCredentials struct {
	AccessKeyID     string
	SecretAccessKey string
	SessionToken    string
}

AWSCredentials are static AWS credentials.

type Cache

type Cache interface {
	Get(key string) (string, bool)
	Set(key, value string) error
}

Cache stores tokens between invocations (backed by the apic session).

type DigestState

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

DigestState remembers the challenges seen in one invocation, per server, so a second request to the same server sends its Authorization on the first try with the nonce count incremented. A Runner holds one.

func NewDigestState

func NewDigestState() *DigestState

NewDigestState returns an empty state.

type DigestTransport

type DigestTransport struct {
	Base http.RoundTripper
	User string
	Pass string
	// Host is the scheme://host the request addressed; a challenge from
	// any other host (one a redirect led to) is left unanswered, since
	// the credentials belong to the host the file names. Empty pins the
	// transport to the first request it sends.
	Host   string
	State  *DigestState // may be nil: then every request is challenged
	Rounds int
	// Challenged is set when a 401 was answered; Answered when the
	// Authorization header went out (on the first or the second try).
	Challenged, Answered bool
	// contains filtered or unexported fields
}

DigestTransport answers a server's Digest challenge on behalf of one request: it sends the request, and on a 401 that carries a Digest challenge it sends it once more with the Authorization header computed from the credentials. Rounds counts the requests it sent.

func (*DigestTransport) RoundTrip

func (d *DigestTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type Env

type Env struct {
	Cache     Cache
	Client    *http.Client // used for token endpoints
	AllowExec bool
	Stderr    io.Writer // device-code and browser sign-in prompts
	Now       func() time.Time
	// Interactive says a person is at a terminal, so a grant that needs a
	// browser may start one; false under --json, in MCP and in tests.
	Interactive bool
	// OpenBrowser opens a URL for the person; nil means the system's
	// opener. Tests inject one that visits the URL themselves.
	OpenBrowser func(url string) error
}

Env is what Apply needs from the caller.

type JetBrains

type JetBrains struct {
	Spec *Spec
	// UseIDToken is the configuration's "Use ID Token": $auth.token then
	// gives the ID token rather than the access token.
	UseIDToken bool
	// Ignored names the fields apic does not act on; validate warns about
	// each.
	Ignored []string
}

JetBrains is a JetBrains HTTP Client `Security.Auth` configuration mapped onto an oauth2 spec, so {{$auth.token("name")}} runs the same grant and shares the same token cache as `# @auth oauth2`.

func FromJetBrains

func FromJetBrains(fields map[string]any, render func(string) (string, error)) (*JetBrains, error)

FromJetBrains maps a Security.Auth entry. render substitutes the {{placeholders}} a string field may hold; the result is checked like a written `# @auth oauth2`. The Implicit grant is refused: it is deprecated by OAuth 2.1, and Authorization Code with PKCE replaces it.

type Spec

type Spec struct {
	Type    string
	Args    []string
	Options map[string]string
	Raw     string
}

Spec is a parsed `# @auth` value. Args holds positional arguments and Options holds key=value arguments; both may still contain {{placeholders}} until the runner renders them.

func Parse

func Parse(raw string) (*Spec, error)

Parse splits an auth spec such as `basic {{user}} {{password}}` or `aws service=execute-api region=eu-west-2`.

func (*Spec) APIKeyPlacement

func (s *Spec) APIKeyPlacement() (header, query string)

APIKeyPlacement reports where an apikey spec puts the key: the header name (default X-Api-Key) or the query parameter, for describe and the curl export.

func (*Spec) Render

func (s *Spec) Render(fn func(string) (string, error)) (*Spec, error)

Render returns a copy of the spec with fn applied to every argument and option value (used to substitute {{placeholders}}).

func (*Spec) Texts

func (s *Spec) Texts() []string

Texts returns every string in the spec that may contain placeholders.

type Tokens

type Tokens struct {
	Access string
	ID     string
}

Tokens are what an OAuth2 grant returned: the access token, and the ID token when the provider sent one (an OpenID Connect scope).

func OAuth2Tokens

func OAuth2Tokens(ctx context.Context, s *Spec, env *Env, needID bool) (Tokens, error)

OAuth2Tokens runs a rendered oauth2 spec's grant, or reuses the cached result, as `# @auth oauth2` does. JetBrains' {{$auth.token("name")}} and {{$auth.idToken("name")}} read it. needID says the caller wants the ID token, so a cached entry without one is not enough.

Jump to

Keyboard shortcuts

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