/* pic's only credential code. A key is fetched into a caller buffer just
* before a request and wiped right after; it is never journaled, logged or
* put in an error message. Keys come from pic's credential store, the models file (a
* literal) or an environment variable, in that order: rows of picu_credential
* in ~/.pic/pic.sqlite, each sealed with ChaCha20-Poly1305 under a master
* key that never touches the database; a subscription sign-in's tokens are
* sealed the same way (see "subscription sign-in" below). The master key comes from the
* platform's secret_key hook (platform.h): on a host, a passphrase stretched
* with PBKDF2-HMAC-SHA256. It is asked for only when a stored key is needed,
* and kept for the life of the process. */
#ifndef PIC_CRED_H
#define PIC_CRED_H
#include <stddef.h>
#include <stdint.h>
/* The size of a buffer that holds any key pic accepts, its NUL included: a
* key is at most PIC_CRED_KEY_CAP - 1 bytes, at login and at use alike. */
#define PIC_CRED_KEY_CAP 512
/* The size of a buffer for what pic_cred_get returns: an API key, or a
* subscription's access token (a signed token, longer than any key). */
#define PIC_CRED_TOKEN_CAP 8192
/* The largest subscription credential (its JSON object) pic stores. */
#define PIC_CRED_OAUTH_CAP 32768
/* Fetches PROVIDER's key, in Pi's order: the store's credential for PROVIDER
* (unlocking the store, which may ask for the passphrase), else LITERAL (the
* models file's), else the variable ENV. A stored credential that cannot be
* had is an error: it never falls back to the variable. A stored subscription sign-in gives
* its access token, refreshed first when it expires within a minute. 0 with
* the key in buf; 1 when nothing
* is configured or stored (a server that needs no key); -1 with err (never
* the value), naming `pic login`, when no key can be had. */
int pic_cred_get(const char *provider, const char *env, const char *literal, char *buf, size_t cap, char *err,
size_t errcap);
/* Overwrites n bytes in a way the compiler may not remove. */
void pic_cred_wipe(void *p, size_t n);
/* Seals KEY for PROVIDER into the store (replacing any), unlocking it
* first, or creating it (a new passphrase) when it has no master key yet. 0,
* or -1 with err. */
int pic_cred_login(const char *provider, const char *key, char *err, size_t errcap);
/* Removes PROVIDER's stored key: 1 removed, 0 none was stored, -1. */
int pic_cred_logout(const char *provider);
/* Whether PROVIDER has a stored key (no unlock needed): 1 or 0. */
int pic_cred_stored(const char *provider);
/* Calls fn for each stored credential's name and kind ("api_key", or
* "oauth" for a subscription sign-in), oldest first, until it returns
* nonzero; used_ms 0 when never used. Values are never read. 0 or -1. */
int pic_cred_each(int (*fn)(void *ctx, const char *name, const char *kind, long long created_ms, long long used_ms),
void *ctx);
/* Where a request for PROVIDER would take its credential from, without
* unlocking anything, in the order pic_cred_get uses: a stored API key or
* sign-in, the models file's literal, the variable ENV, or nothing. */
typedef enum { PIC_CRED_NONE, PIC_CRED_LITERAL, PIC_CRED_ENV, PIC_CRED_STORED_KEY, PIC_CRED_STORED_OAUTH } pic_cred_source;
pic_cred_source pic_cred_source_of(const char *provider, const char *env, const char *literal);
/* The source in use as a phrase, naming what it shadows: "stored key (in use;
* FOO_API_KEY also set)", "FOO_API_KEY (in use)", or "none". */
void pic_cred_describe(const char *provider, const char *env, const char *literal, char *out, size_t cap);
/* ---- named keys -----------------------------------------------------------
* A provider may hold several keys. Its own row (named PROVIDER, the label
* "default") is the one `pic login` has always written; more are rows named
* PROVIDER:LABEL, each sealed under its own name. The variable is the label
* "env" and the models file's literal "file". Which one a request uses: the
* label given for this run (pic_cred_override), else the setting
* activeKey:PROVIDER, else the provider's own row, else its oldest named row,
* else the models file's literal, else the variable. */
#define PIC_CRED_NAME_CAP 160
#define PIC_CRED_LABEL_CAP 40
/* A provider name is at most PIC_CRED_PROVIDER_CAP - 1 bytes and has no ':'
* (pic_model's provider field is this size). */
#define PIC_CRED_PROVIDER_CAP 64
/* LABEL is 1-32 of a-z, 0-9, '-' and '_', and not "env" or "file". 0, or -1 with err. */
int pic_cred_label_check(const char *label, char *err, size_t errcap);
/* Seals KEY as PROVIDER's key LABEL (NULL or "default": its own row), as pic_cred_login does. */
int pic_cred_login_as(const char *provider, const char *label, const char *key, char *err, size_t errcap);
/* Which credential a request used: its name (the health key: a row's name,
* env:VAR:HASH or file:PROVIDER:HASH, HASH twelve hex digits of a salted
* hash of the value) and its label. */
typedef struct {
char name[PIC_CRED_NAME_CAP];
char label[PIC_CRED_LABEL_CAP];
} pic_cred_used;
/* pic_cred_get, saying which credential it gave (USED may be NULL). */
int pic_cred_get_as(const char *provider, const char *env, const char *literal, char *buf, size_t cap, pic_cred_used *used,
char *err, size_t errcap);
/* The label PROVIDER's requests use for this process only (`--key`, RPC's
* set_credential); a NULL label clears PROVIDER's, a NULL provider all.
* -1 when it cannot be kept (every slot taken, or a name too long), else 0. */
int pic_cred_override(const char *provider, const char *label);
/* Whether PROVIDER has the key LABEL (default, a stored name, env when ENV is
* set, file when LITERAL is given): 1 or 0. */
int pic_cred_has(const char *provider, const char *label, const char *env, const char *literal);
/* Rewrites MSG in place so that no part of KEY that a provider might quote
* survives: the whole key, its first eight or its last four characters,
* anywhere, each with the token around it, become "[key]". */
void pic_cred_scrub(char *msg, const char *key);
/* Makes LABEL PROVIDER's active key (the setting activeKey:PROVIDER), when
* PROVIDER has it (ENV and LITERAL as a request has them). 0, or -1 with err. */
int pic_cred_use(const char *provider, const char *label, const char *env, const char *literal, char *err, size_t errcap);
/* One of PROVIDER's credentials, as pic_cred_entries lists them. */
typedef struct {
const char *provider, *label, *name;
const char *kind; /* "api_key", "oauth", "env" or "file" */
const char *env; /* the variable, for "env" */
int active; /* the one a request would use */
long long created_ms, used_ms; /* stored rows only; 0 otherwise */
} pic_cred_entry;
/* Calls fn for each of PROVIDER's credentials: its own row, its named rows
* (oldest first), the variable ENV when set and the models file's LITERAL
* when given, until fn returns nonzero. Values are never handed out. 0 or -1. */
int pic_cred_entries(const char *provider, const char *env, const char *literal,
int (*fn)(void *ctx, const pic_cred_entry *e), void *ctx);
/* ---- what pic remembers of a key ------------------------------------------
* Recorded from real replies, per credential name, in picu_credential_health;
* never with key text. A transient failure (a 5xx, an overload, a short 429)
* or another refusal says nothing about the key and changes nothing. */
typedef enum {
PIC_KEY_UNKNOWN, /* nothing recorded */
PIC_KEY_OK, /* the last reply came back */
PIC_KEY_INVALID, /* refused: 401, 403 */
PIC_KEY_CREDIT, /* out of credit or quota */
PIC_KEY_LIMITED, /* rate-limited until until_ms */
PIC_KEY_TRANSIENT, /* retried as before */
PIC_KEY_OTHER /* any other failure */
} pic_key_state;
typedef struct {
pic_key_state state;
int status; /* the HTTP status it was learnt from; 0 none */
long long until_ms; /* limited: when it lifts */
long long checked_ms; /* when it was learnt; for a failure, since when */
double remaining; /* credit left, when a provider says */
int has_remaining;
char currency[8]; /* remaining's unit: "$", "\xc2\xa5", a code; "" is "$" */
long long probed_ms; /* when a free check last ran, whatever it learnt; 0 never */
char reason[200]; /* the provider's words, short */
} pic_key_health;
/* "ok", "invalid", "credit", "limited", "transient", "other" or "unknown". */
const char *pic_key_state_name(pic_key_state s);
/* Records H for NAME (ok, invalid, credit and limited only; checked_ms is
* now when 0; a failure already recorded keeps its first time). 0 or -1. */
int pic_cred_health_note(const char *name, const pic_key_health *h);
/* NAME's state into h: 1, or 0 with h->state PIC_KEY_UNKNOWN when none is kept. */
int pic_cred_health_of(const char *name, pic_key_health *h);
/* Notes that a free check of NAME ran at NOW_MS and learnt nothing about the
* key (no answer, a status that says nothing): a key with no record gets
* "other" with STATUS and REASON; one with a record keeps it. 0 or -1. */
int pic_cred_health_probed(const char *name, long long now_ms, int status, const char *reason);
/* The name the credential in use for PROVIDER is kept under, without
* opening anything (pic_cred_get_as would give the same): 0, or -1 when there
* is none. */
int pic_cred_active(const char *provider, const char *env, const char *literal, pic_cred_used *out);
/* How a refused request is read, and the words for a key's state: a bundled
* component knows each vendor's wording (patterns as data) and decides the
* swap prompt's choices; the composition root registers it. Core only
* dispatches, and with nothing registered falls back on the status alone
* and plain words. classify fills h (state, reason, until_ms) from the
* status, the error body and its message, the rate-limit header lines and
* Retry-After; message is the error a request ends with; headline the swap
* prompt's first line; offers its choices as letters (s another key, only
* with HAVE_OTHER; m another model; w wait; l log in again); phrase a
* state for a list; alert the footer's warning ("" none); bad whether the
* key should not be used now. No text ever holds a key. */
typedef struct {
void (*classify)(const char *provider, int status, const char *body, const char *message, const char *ratelimit,
const char *retry_after, long long now_ms, pic_key_health *h);
void (*message)(const char *provider, const char *label, const pic_key_health *h, long long now_ms, char *out,
size_t cap);
void (*headline)(const char *provider, const char *label, const pic_key_health *h, long long now_ms, char *out,
size_t cap);
const char *(*offers)(pic_key_state state, int have_other);
void (*phrase)(const pic_key_health *h, long long now_ms, char *out, size_t cap);
void (*alert)(const pic_key_health *h, long long now_ms, char *out, size_t cap);
int (*bad)(const pic_key_health *h, long long now_ms);
void (*until)(long long until_ms, long long now_ms, char *out, size_t cap);
} pic_cred_health_ops;
void pic_cred_health_register(const pic_cred_health_ops *ops);
void pic_cred_classify(const char *provider, int status, const char *body, const char *message, const char *ratelimit,
const char *retry_after, long long now_ms, pic_key_health *h);
void pic_cred_failure_message(const char *provider, const char *label, const pic_key_health *h, long long now_ms,
char *out, size_t cap);
void pic_cred_key_headline(const char *provider, const char *label, const pic_key_health *h, long long now_ms, char *out,
size_t cap);
const char *pic_cred_key_offers(pic_key_state state, int have_other);
void pic_cred_key_phrase(const pic_key_health *h, long long now_ms, char *out, size_t cap);
void pic_cred_key_alert(const pic_key_health *h, long long now_ms, char *out, size_t cap);
int pic_cred_key_bad(const pic_key_health *h, long long now_ms);
/* "15:45 (38 min)". */
void pic_cred_key_until(long long until_ms, long long now_ms, char *out, size_t cap);
/* ---- subscription sign-in ---------------------------------------------------
* The flows are provider code, outside core: the composition root registers
* them here. A subscription credential is a JSON object with at least
* "access" (the bearer token), "refresh" and "expires" (ms since the epoch);
* the flow may keep more fields in it. It is sealed whole, like a key. */
#define PIC_CRED_NO_BROWSER 1 /* print the URL and take a pasted code; open no browser */
#define PIC_CRED_NO_TERMINAL 2 /* messages to stderr and nothing pasted: stdout is a protocol (RPC) */
#define PIC_CRED_PIPE 4 /* the terminal interface's child: JSON lines out, pasted lines on stdin */
typedef struct {
/* PROVIDER's sign-in label ("Sign in with ..."), or NULL when it has none. */
const char *(*label)(const char *provider);
/* Signs in on the terminal (FLAGS: PIC_CRED_NO_BROWSER, PIC_CRED_NO_TERMINAL). 0 with *kind
* ("oauth", or "api_key" for a flow that hands back a key) and *secret
* (malloc'd: the credential JSON, or the key; the caller wipes and frees
* it); -1 with err. */
int (*login)(const char *provider, int flags, const char **kind, char **secret, char *err, size_t errcap);
/* Exchanges CRED's refresh token: 0 with the new credential JSON in *out
* (malloc'd); -1 with err, never a token in it. */
int (*refresh)(const char *provider, const char *cred, char **out, char *err, size_t errcap);
/* The only address prefix (scheme, host, "/") PROVIDER's subscription
* token may be sent to, or NULL when its sign-in stores a plain key. */
const char *(*origin)(const char *provider);
} pic_cred_oauth_ops;
void pic_cred_oauth_register(const pic_cred_oauth_ops *ops);
/* Where PROVIDER's subscription token may be sent (cred ops' origin), or NULL. */
const char *pic_cred_oauth_origin(const char *provider);
/* PROVIDER's sign-in label, or NULL when it has no subscription sign-in. */
const char *pic_cred_oauth_label(const char *provider);
/* Unlocks the store (or makes it), runs PROVIDER's sign-in and seals what it
* returns. 0, or -1 with err. */
int pic_cred_oauth_login(const char *provider, int flags, char *err, size_t errcap);
/* After a request was refused with STALE (the access token it sent): the
* current access token in buf, refreshed unless another process already
* replaced STALE. One process refreshes at a time (a lock beside the user
* database), so a refresh token that rotates is spent once. 0, or -1 with
* err. */
int pic_cred_refresh(const char *provider, const char *stale, char *buf, size_t cap, char *err, size_t errcap);
/* A key check pic_cred_get and pic_cred_login share: 0, or -1 with err
* (never the value) when KEY is empty, too long or not header-safe. */
int pic_cred_check(const char *what, const char *key, char *err, size_t errcap);
/* Whether a request for PROVIDER (with the model's ENV and LITERAL) would
* read the store while it is still locked: 1 or 0. An interface uses it to
* ask for the passphrase before it starts a request in a child. */
int pic_cred_needs_unlock(const char *provider, const char *env, const char *literal);
/* Unlocks the store now (asking for the passphrase if need be). 0, or -1
* with err; a wrong passphrase is an error, never a garbage key. */
int pic_cred_unlock(char *err, size_t errcap);
/* The store's state, asking nothing: PIC_CRED_NEW (no master key yet, so a
* new passphrase is wanted), PIC_CRED_LOCKED, or PIC_CRED_OPEN. */
enum { PIC_CRED_NEW, PIC_CRED_LOCKED, PIC_CRED_OPEN };
int pic_cred_state(void);
/* Unlocks the store, or makes it when it is new (the passphrase from the
* platform's secret_key, as always). 0, or -1 with err. */
int pic_cred_prepare(char *err, size_t errcap);
/* Handing the unlocked master key to a child pic (the interface's request
* processes) without asking again, and without it touching argv, the
* environment's values, the journal or any file:
* the parent calls pic_cred_handoff() before fork; it returns the read end
* of a pipe that already holds the 32 key bytes (write end closed), or -1
* when the store is not unlocked. The fd is close-on-exec; the child clears
* that and sets PIC_KEY_FD to its number (only the number is in the
* environment), and the parent closes its copy after fork.
* the child calls pic_cred_adopt() first thing: it reads the bytes, closes
* the fd and unsets PIC_KEY_FD, so nothing it runs inherits either. The
* bytes are checked against the store's verifier before first use.
* A pipe holds the bytes only in the kernel; nothing reaches a disk. */
int pic_cred_handoff(void);
void pic_cred_adopt(void);
/* Sealing a component's own rows under the master key (remote control's keys and devices,
* docs/design/remote-protocol.md): box seals N bytes of PT bound to AAD into OUT (N +
* PIC_CRED_OVERHEAD bytes), unbox opens them into PT. Both need the store unlocked
* (pic_cred_unlock or pic_cred_prepare first) and ask for nothing. 0, or -1 with err (unbox: a
* row that does not open under this key, with PT wiped). */
int pic_cred_box(const char *aad, const void *pt, size_t n, unsigned char *out, char *err, size_t errcap);
int pic_cred_unbox(const char *aad, const unsigned char *in, size_t n, void *pt, char *err, size_t errcap);
/* ---- the primitives, exposed for the unit tests ------------------------ */
#define PIC_CRED_KEY 32
#define PIC_CRED_NONCE 12
#define PIC_CRED_TAG 16
#define PIC_CRED_OVERHEAD (PIC_CRED_NONCE + PIC_CRED_TAG)
/* Seals N bytes of PT under KEY with AAD bound: out gets nonce, ciphertext
* and tag (N + PIC_CRED_OVERHEAD bytes), with a fresh random nonce. 0 or -1
* (no entropy). */
int pic_cred_seal(const unsigned char key[PIC_CRED_KEY], const char *aad, const void *pt, size_t n, unsigned char *out);
/* Opens what pic_cred_seal made (N bytes in all) into pt (N -
* PIC_CRED_OVERHEAD bytes): 0, or -1 with pt wiped when the key, the AAD or
* any byte is wrong. */
int pic_cred_open(const unsigned char key[PIC_CRED_KEY], const char *aad, const unsigned char *in, size_t n, void *pt);
/* PBKDF2-HMAC-SHA256 to a 32-byte key. */
void pic_cred_kdf(const void *pass, size_t n, const unsigned char *salt, size_t saltn, uint32_t iterations,
unsigned char out[PIC_CRED_KEY]);
/* Forgets the cached master key (tests). */
void pic_cred_lock(void);
#endif