Documentation
¶
Overview ¶
Package iapclient lets a program act as an agent:user principal against an identity-aware proxy whose issuer mints short-lived, host-bound access tokens (iap-authz's agent tokens).
A person registers a machine and program once in the browser (Client.Login: loopback redirect + PKCE). The issuer returns a refresh credential, valid about 30 days, which goes into a Store (macOS Keychain, the Secret Service through secret-tool, or an explicitly chosen 0600 file). From then on a TokenSource mints an access token for one session on one exact host, and a Transport sends it as `Proxy-Authorization: Bearer <token>`.
Invariants this package enforces:
- tokens are minted for and sent to https URLs only, on hosts under the issuer's own domain or a domain it advertised at login;
- a token is minted for exactly the request's host and sent only there, never on a redirect to another host;
- access tokens live in memory only; the refresh credential lives only in the Store;
- neither appears in an error, a String/fmt/slog rendering (Secret), a process argv (stores use stdin), or stdout.
The package imports only the standard library.
Example ¶
Calling a protected host from Go, after `iap login` on this machine.
package main
import (
"context"
"fmt"
"io"
"log"
"net/http"
"github.com/R167/iap/iapclient"
)
func main() {
store, err := iapclient.OpenStore(iapclient.StoreAuto) // or StoreFile, chosen explicitly
if err != nil {
log.Fatal(err)
}
client, err := iapclient.New(iapclient.Config{
Issuer: "https://access.example.com", // your issuer
Store: store,
})
if err != nil {
log.Fatal(err)
}
// The session names this run; tokens are minted per (session, host).
hc, err := client.HTTPClient("nightly-report")
if err != nil {
log.Fatal(err) // e.g. not logged in
}
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "https://app.example.com/api/status", nil)
if err != nil {
log.Fatal(err)
}
resp, err := hc.Do(req) // a *iapclient.ForbiddenError when no grant covers you
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(resp.Status, len(body))
}
Output:
Index ¶
- Constants
- Variables
- func CheckStore(ctx context.Context, store Store) error
- func DefaultDir() (string, error)
- func DefaultFileStoreDir() (string, error)
- func DefaultMachine() string
- func HasDisplay() bool
- func NoEchoStdin() (read func() (string, error), restore func(), err error)
- func OpenURL(ctx context.Context, u string) error
- func ParseIssuer(raw string) (string, error)
- func PatternOf(principal string) string
- func RequestCheck(challenge string) string
- func SanitizeSegment(s string) string
- func SaveState(dir, program string, s State) error
- func SaveStateFile(dir string, f StateFile) error
- func StatePath(dir string) string
- func StdinLine() (string, error)
- func ValidSegment(s string) bool
- type Client
- func (c *Client) AllowedSuffixes() []string
- func (c *Client) CheckURL(raw string) (string, error)
- func (c *Client) HTTPClient(session string) (*http.Client, error)
- func (c *Client) Issuer() string
- func (c *Client) Login(ctx context.Context, opts LoginOptions) (Registration, error)
- func (c *Client) Logout(ctx context.Context) (account string, err error)
- func (c *Client) Program() string
- func (c *Client) State() State
- func (c *Client) Status(ctx context.Context) Status
- func (c *Client) Store() Store
- func (c *Client) TokenSource(session string) (*TokenSource, error)
- type Config
- type CredentialLostError
- type FileStore
- func (f FileStore) Delete(_ context.Context, account string) error
- func (f FileStore) Exists(_ context.Context, account string) (bool, error)
- func (f FileStore) Load(_ context.Context, account string) (Secret, error)
- func (f FileStore) Location(string) string
- func (FileStore) Name() string
- func (f FileStore) Save(_ context.Context, account string, cred Secret) error
- type ForbiddenError
- type HostNotAllowedError
- type IssuerMismatchError
- type KeychainStore
- func (k KeychainStore) Delete(ctx context.Context, account string) error
- func (k KeychainStore) Exists(ctx context.Context, account string) (bool, error)
- func (k KeychainStore) Load(ctx context.Context, account string) (Secret, error)
- func (k KeychainStore) Location(account string) string
- func (KeychainStore) Name() string
- func (k KeychainStore) Save(ctx context.Context, account string, cred Secret) error
- type LoginOptions
- type Registration
- type Secret
- func (Secret) AppendBinary([]byte) ([]byte, error)
- func (Secret) AppendText([]byte) ([]byte, error)
- func (Secret) Format(f fmt.State, _ rune)
- func (Secret) GoString() string
- func (s Secret) IsZero() bool
- func (Secret) LogValue() slog.Value
- func (Secret) MarshalBinary() ([]byte, error)
- func (Secret) MarshalJSON() ([]byte, error)
- func (Secret) MarshalJSONTo(*jsontext.Encoder) error
- func (Secret) MarshalText() ([]byte, error)
- func (s Secret) Reveal() string
- func (Secret) String() string
- type SecretServiceStore
- func (s SecretServiceStore) Delete(ctx context.Context, account string) error
- func (s SecretServiceStore) Exists(ctx context.Context, account string) (bool, error)
- func (s SecretServiceStore) Load(ctx context.Context, account string) (Secret, error)
- func (s SecretServiceStore) Location(account string) string
- func (SecretServiceStore) Name() string
- func (s SecretServiceStore) Save(ctx context.Context, account string, cred Secret) error
- type State
- type StateFile
- type Status
- type Store
- type Token
- type TokenSource
- type Transport
Examples ¶
Constants ¶
const ( StoreAuto = "auto" StoreKeychain = "keychain" StoreSecretService = "secret-service" StoreFile = "file" )
Store names accepted by OpenStore.
const DefaultHeadlessTimeout = 10 * time.Minute
DefaultHeadlessTimeout bounds a headless login, which waits for a person to sign in on another device and paste the code back.
const DefaultLoginTimeout = 5 * time.Minute
DefaultLoginTimeout bounds the wait for the browser consent.
const DefaultService = "iap-authz"
DefaultService names the Keychain / Secret Service items this package writes.
const SegmentPattern = `^[a-z0-9][a-z0-9._-]{0,62}$`
SegmentPattern is the pattern machine, program and session must match.
Variables ¶
var ( // ErrNotLoggedIn: no registration is saved. ErrNotLoggedIn = errors.New("not logged in") // ErrInvalidGrant: the issuer refused the refresh credential or login code. ErrInvalidGrant = errors.New("invalid_grant: the registration was revoked or expired, or the code was used") // ErrRefreshReused: the issuer saw a refresh credential it had already // rotated away presented after its grace window (a copy of the credential // in use somewhere else) and revoked the registration. It wraps // ErrInvalidGrant. ErrRefreshReused = fmt.Errorf("%w (here: a refresh credential already rotated away was presented again, so the issuer revoked the registration; log in again, and if no other copy of this machine's credential should exist, treat it as leaked)", ErrInvalidGrant) )
var ( // ErrNoCredential: the store has no credential for the account. ErrNoCredential = errors.New("no stored credential") // ErrNoKeyring: auto selection found no OS keyring. The file store is // never chosen in its place; the caller must opt in to it. ErrNoKeyring = errors.New("no OS keyring available") )
ErrSecretServiceUnavailable: secret-tool ran but could not reach an unlocked Secret Service (typically a headless machine with no D-Bus session or no keyring daemon).
Functions ¶
func CheckStore ¶
CheckStore proves store can keep a credential the way Login will: it saves a random throwaway value under a probe account, checks it is there, and deletes it. Asking alone is not enough (the Keychain answers "not found" for a locked keychain, and a locked Secret Service can answer lookups). No real credential is touched. Login calls it before the person approves anything.
func DefaultFileStoreDir ¶
DefaultFileStoreDir is $XDG_STATE_HOME/iap, else ~/.local/state/iap.
func DefaultMachine ¶
func DefaultMachine() string
DefaultMachine is the short hostname, sanitised, else "mac" on macOS and "host" elsewhere.
func HasDisplay ¶
func HasDisplay() bool
HasDisplay reports whether OpenURL can plausibly open a browser the user sees: not over SSH on macOS, and only with a display elsewhere.
func NoEchoStdin ¶
NoEchoStdin returns a reader of one stdin line and a restore func. When stdin is a terminal it turns echo off with stty (saving the state with `stty -g`) and restore puts the saved state back; restore is idempotent and safe to call from another goroutine while read is blocked. When stdin is not a terminal (a pipe, a file, /dev/null), read is StdinLine and restore does nothing.
func OpenURL ¶
OpenURL opens u in the desktop browser: `open` on macOS, `xdg-open` elsewhere. It fails on a machine with no display.
func ParseIssuer ¶
ParseIssuer checks that raw is https://<host> with at least three labels (the issuer's own domain is the host minus its first label) and nothing else: no port, path, query, fragment or userinfo. It returns the issuer normalised (lowercase host, no trailing slash). The refresh credential is posted there, so nothing looser is accepted.
func PatternOf ¶
PatternOf maps agent:user:<e>:<m>:<p>:<s> to its registration pattern agent:user:<e>:<m>:<p>:*.
func RequestCheck ¶
RequestCheck is the mix-up check the issuer's headless consent page shows for a PKCE challenge (two logins at once, the wrong tab): base32 of the first five bytes of sha256("iap login request\x00" || challenge), as XXXX-XXXX. It is derived from the public challenge, so anyone holding the link can quote it: it never proves a link is yours, and authorizes nothing.
func SanitizeSegment ¶
SanitizeSegment lowercases s and maps it onto the segment rule, or "".
func SaveStateFile ¶
SaveStateFile writes f to dir (0600 in a 0700 directory), atomically: a temp file in dir, synced, then renamed over the old one, so a reader never sees half a file.
func StdinLine ¶
StdinLine reads one line from os.Stdin, byte by byte so nothing past the newline is consumed.
func ValidSegment ¶
ValidSegment reports whether s is a valid machine, program or session.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client mints host-bound access tokens from a saved registration.
func New ¶
New validates cfg and loads the saved state. Being logged out is not an error here; it is reported when a credential is needed.
func (*Client) AllowedSuffixes ¶
AllowedSuffixes are the domains tokens may be minted for and sent to: the issuer's own domain, plus those it advertised at login (when the saved registration is this issuer's). An advertised suffix that contains the issuer's domain (".example.com" for ".iap.example.com") would widen it to hosts the issuer never vouched for, and one under it adds nothing, so both are dropped.
func (*Client) CheckURL ¶
CheckURL validates raw (https, no userinfo, a plain host under AllowedSuffixes) and returns its lowercase host.
func (*Client) HTTPClient ¶
HTTPClient returns an *http.Client for session whose Transport adds the credential (see Transport) over http.DefaultTransport.
func (*Client) Login ¶
func (c *Client) Login(ctx context.Context, opts LoginOptions) (Registration, error)
Login registers this machine and program with the issuer: it listens on 127.0.0.1:<port>, sends a browser to the issuer's consent page with a PKCE S256 challenge and a random state, receives a one-time code on /callback, trades it (with the verifier) for the refresh credential, stores that in the Store and saves the state. A person must approve in the browser; the issuer decides who may. With opts.Headless the code comes from the person instead (see LoginOptions.Headless); everything after it is the same.
func (*Client) Logout ¶
Logout deletes the stored credential and forgets the registration. The registration itself stays valid at the issuer until revoked there.
func (*Client) Program ¶
Program is the program segment whose registration the client uses (after a Login, the one it registered).
func (*Client) Status ¶
Status reports the registration and whether its credential is stored, without reading it into the output.
func (*Client) TokenSource ¶
func (c *Client) TokenSource(session string) (*TokenSource, error)
TokenSource returns a source for session, which must match SegmentPattern.
type Config ¶
type Config struct {
// Issuer is the token issuer, https://<host> with nothing after it.
// Required; no default is built in.
Issuer string
// Dir holds the non-secret state file (StatePath). Default:
// os.UserConfigDir()/iap.
Dir string
// Store keeps the refresh credential. Required (see OpenStore).
Store Store
// Program is the program segment whose registration the client uses, and
// the one Login registers by default ("cli" if empty). Each program has
// its own registration and stored credential (StateFile).
Program string
// HTTPClient talks to the issuer. Default: 30s timeout, no redirects.
HTTPClient *http.Client
// Now is the clock; default time.Now.
Now func() time.Time
// LegacyIssuer is the issuer a saved state without an issuer field
// belongs to (written before the field existed: the tool's built-in
// default). Empty: such a state belongs to no issuer, and its credential
// is never sent anywhere.
LegacyIssuer string
}
Config configures a Client.
type CredentialLostError ¶
type CredentialLostError struct {
Principal string
Issuer string
ExpiresAt time.Time
Store string
Err error
}
CredentialLostError: the issuer registered the agent and handed over its refresh credential, but the store refused it, so the credential is gone. The registration exists at the issuer (and can't be used by anyone) until it expires or is revoked.
func (*CredentialLostError) Error ¶
func (e *CredentialLostError) Error() string
func (*CredentialLostError) Unwrap ¶
func (e *CredentialLostError) Unwrap() error
type FileStore ¶
type FileStore struct {
Dir string
}
FileStore keeps credentials in Dir/credentials.json (a JSON object, account → credential), mode 0600 in a 0700 directory. It is for machines with no keyring and must be chosen explicitly: anyone who can read the file as you (or read your disk) holds the credential. It refuses to read or write when the directory or file is a symlink, or is readable, writable or executable by group or others. It does not work on Windows, whose permission bits it cannot check.
type ForbiddenError ¶
type ForbiddenError struct{ Principal, Host, Audience, Issuer string }
ForbiddenError: the issuer will not mint for this principal on this host, because no grant covers it. Ask the issuer's admin for one. For a federated audience (Audience set, Host empty), the issuer's policy entry for that audience does not list the agent, or its owner may not reach the entry's host.
func (*ForbiddenError) Error ¶
func (e *ForbiddenError) Error() string
type HostNotAllowedError ¶
type HostNotAllowedError struct {
URL string
Suffixes []string
// contains filtered or unexported fields
}
HostNotAllowedError: the URL is not https, or its host is not under a domain the issuer mints for.
func (*HostNotAllowedError) Error ¶
func (e *HostNotAllowedError) Error() string
type IssuerMismatchError ¶
type IssuerMismatchError struct{ Saved, Configured string }
IssuerMismatchError: the saved registration belongs to another issuer, so its refresh credential is not sent to this one.
func (*IssuerMismatchError) Error ¶
func (e *IssuerMismatchError) Error() string
type KeychainStore ¶
type KeychainStore struct {
Service string
}
KeychainStore keeps the credential in the macOS login Keychain as a generic password, service Service (default "iap-authz"), account = the registration principal. It drives /usr/bin/security; writes go through `security -i` reading the command from stdin, so the credential is never on any process's argv.
func (KeychainStore) Delete ¶
func (k KeychainStore) Delete(ctx context.Context, account string) error
func (KeychainStore) Location ¶
func (k KeychainStore) Location(account string) string
func (KeychainStore) Name ¶
func (KeychainStore) Name() string
type LoginOptions ¶
type LoginOptions struct {
Machine string // default DefaultMachine()
Program string // default Config.Program, else "cli"
// Port is the loopback callback port; 0 picks a free one. Fix it (1024–
// 65535) to forward it over SSH from another machine's browser.
Port int
// OpenBrowser opens the consent URL; nil prints it only. OpenURL is the
// platform default. Not used by a headless login.
OpenBrowser func(ctx context.Context, url string) error
// Prompt receives the consent URL and instructions (default os.Stderr).
Prompt io.Writer
Timeout time.Duration // default DefaultLoginTimeout, or DefaultHeadlessTimeout
// Headless logs in without a loopback listener or a browser on this
// machine: the person opens the printed URL on any device, approves, and
// the issuer shows a one-time code to paste back here. The issuer accepts
// the code only with the PKCE verifier, which never leaves this process.
Headless bool
// ReadCode reads the pasted code (headless only). Default: one line from
// os.Stdin, with terminal echo off (stty) while reading when stdin is a
// terminal, restored however Login returns. Login never prints or logs
// what it reads. A caller that wants echo restored on SIGINT too must
// handle the signal itself (the iap CLI does).
ReadCode func() (string, error)
// StoreFallback records that Config.Store was chosen only because no OS
// keyring worked (State.StoreFallback), so the next login tries the
// keyring again instead of treating the store as the person's choice.
StoreFallback bool
// SaveFallback is called when Config.Store refuses the refresh credential
// after the code exchange, while the credential is still in memory, with
// the store's name and error (never a secret). A non-nil Store it returns
// is tried instead; on success the login proceeds with that store,
// recorded as a fallback (State.StoreFallback). nil keeps the
// CredentialLostError.
SaveFallback func(store string, err error) Store
}
LoginOptions configures Login.
type Registration ¶
type Registration struct {
Issuer string
Account string // the principal pattern, without the trailing ":*"
ExpiresAt time.Time
AudienceSuffixes []string
Store string
Location string
}
Registration is the result of a Login.
type Secret ¶
type Secret struct {
// contains filtered or unexported fields
}
Secret holds a credential (an access token or the refresh credential). It never prints: String, GoString, every fmt verb and slog give "<redacted>", and JSON, text or binary marshalling fails, under encoding/json and encoding/json/v2 alike (each marshalling interface either version, or an encoding.*Appender user, may try first refuses). Reveal is the only way to the value.
func (Secret) AppendText ¶
AppendText and AppendBinary refuse: encoding/json/v2 (as a map key or value) and other encoders try the Appender forms before the Marshal ones.
func (Secret) MarshalBinary ¶
func (Secret) MarshalJSON ¶
func (Secret) MarshalJSONTo ¶
MarshalJSONTo refuses: encoding/json/v2 tries it before MarshalJSON.
func (Secret) MarshalText ¶
type SecretServiceStore ¶
type SecretServiceStore struct {
Service string
// Command is the secret-tool binary; default "secret-tool" from PATH.
Command string
}
SecretServiceStore keeps the credential in the freedesktop Secret Service (GNOME Keyring, KWallet, KeePassXC) through libsecret's secret-tool, with the attributes service=Service (default "iap-authz") and account=<the registration principal>. The credential goes to secret-tool on stdin and comes back on stdout, never on argv.
func (SecretServiceStore) Delete ¶
func (s SecretServiceStore) Delete(ctx context.Context, account string) error
func (SecretServiceStore) Location ¶
func (s SecretServiceStore) Location(account string) string
func (SecretServiceStore) Name ¶
func (SecretServiceStore) Name() string
type State ¶
type State struct {
Issuer string `json:"server,omitempty"`
Account string `json:"account"` // registration principal, the store's key
ExpiresAt time.Time `json:"expires_at"`
// AudienceSuffixes are the extra domains (".example.org") the issuer said
// at login it may mint tokens for, beyond its own domain.
AudienceSuffixes []string `json:"audience_suffixes,omitempty"`
// Store is the store the credential was saved in ("" = auto).
Store string `json:"store,omitempty"`
// StoreFallback: Store was used only because no OS keyring worked at
// login, not chosen. Commands still read the credential from it; the next
// login tries the keyring again.
// omitzero, not omitempty: v2's omitempty would still write false.
StoreFallback bool `json:"store_fallback,omitzero"`
}
State is the non-secret record of one program's registration, kept in Dir/config.json (StateFile). It holds nothing secret.
func (*State) UnmarshalJSON ¶
UnmarshalJSON is UnmarshalJSONFrom for callers on encoding/json (v1).
type StateFile ¶
type StateFile struct {
Registrations map[string]State `json:"registrations,omitempty"`
// TailscaleClientID is the iap CLI's last --client-id for
// api.tailscale.com: a Tailscale trust credential's client ID, an
// identifier, not a secret. iapclient only keeps it.
TailscaleClientID string `json:"tailscale_client_id,omitempty"`
}
StateFile is Dir/config.json: one registration per program segment (claude under Claude Code, cli in a terminal, …), each with its own stored credential, so logging in for one program leaves the others alone.
func LoadStateFile ¶
LoadStateFile reads dir's state file; a missing file is empty. Older layouts are folded in: a top-level "server" is the issuer of every registration that names none (the one-registration-per-program layout before per-registration issuers), and a top-level single registration (account, expires_at, …) becomes its program's entry unless that program already has one.
type Status ¶
type Status struct {
Issuer string
Account string // "" when logged out
ExpiresAt time.Time
Expired bool
AudienceSuffixes []string
Store string // store name
Location string // where the credential lives in that store
Present bool // the store holds a credential for Account
StoreErr error // the store could not be asked
Mismatch error // *IssuerMismatchError when the registration is another issuer's
}
Status describes the registration without any secret.
type Store ¶
type Store interface {
// Name is the store's kind: "keychain", "secret-service" or "file".
Name() string
// Location says where account's credential lives, for status output.
Location(account string) string
Save(ctx context.Context, account string, cred Secret) error
// Load returns ErrNoCredential (wrapped) when there is no credential.
Load(ctx context.Context, account string) (Secret, error)
Exists(ctx context.Context, account string) (bool, error)
Delete(ctx context.Context, account string) error
}
Store keeps the refresh credential, keyed by the registration principal (agent:user:<email>:<machine>:<program>). Access tokens are never stored. No method returns or prints the credential except Load.
type Token ¶
type Token struct {
Value Secret
Host string // the exact host it was minted for
Principal string // agent:user:<email>:<machine>:<program>:<session>
Expiry time.Time // zero when the issuer gave no lifetime
}
Token is an access token minted for one host. Printing a Token shows everything but the credential.
type TokenSource ¶
type TokenSource struct {
// contains filtered or unexported fields
}
TokenSource mints access tokens for one session of the saved registration (principal agent:user:<email>:<machine>:<program>:<session>), one per exact host, and caches each in memory until shortly before it expires. No access token is ever written to disk. Safe for concurrent use; mints are serialised, across processes too (refreshGrant).
func (*TokenSource) FederatedToken ¶
FederatedToken returns a federated token for exactly audience: a relying party outside the issuer's domain that fixes its own audience string (for Tailscale, api.tailscale.com/<client id>). The issuer mints one only when its policy lists that audience for this agent, and the token is never a credential at the issuer's own hosts. It is the caller's to hand to that relying party's own exchange, never to send as Proxy-Authorization. Not cached: each call mints.
type Transport ¶
type Transport struct {
Source *TokenSource
// Base carries the request; nil means http.DefaultTransport.
Base http.RoundTripper
}
Transport is an http.RoundTripper that adds `Proxy-Authorization: Bearer <token>` to a request only when it is https to a host under the client's AllowedSuffixes, with a token minted for exactly that host. It removes any Proxy-Authorization the caller set, so no other credential rides along, and it adds none on a redirect hop whose host differs from the first request's (an issuer-protected host cannot send the client's credential elsewhere, even to another allowed host). Other requests pass through without the header.