Browse documentation
aner.secrets

Credentials

Keep keys outside source with opaque references to native operating system stores, injected environments, managed file storage or one explicitly selected dotenv file.

Implemented

aner.secrets gives an Aner program an opaque reference to a credential. Source code specifies a credential label, environment variable name, or explicit project file and key name; the native runtime resolves its value when the configured consumer uses it. A reference does not expose a raw String, export a value, or load a project file implicitly.

Keep a credential separate from source, notebooks, generated reports, and version control. For interactive development, prefer the native operating system credential service. For headless deployment, use a process environment injected by an external secret manager, or explicitly opt into Aner’s managed file fallback.

Module guide

Use this page to choose a store, create a reference, then pass that reference to a native consumer. There are four source level factories and no raw value getter or separate storage submodules.

TaskReference
Run a program without touching a storeReference only example
Configure, inspect or delete a managed entryHidden input commands
Choose system, injected environment or managed file storageStorage choices, headless deployment
Select a project .env file and key explicitlyProject environment files
See every source function and resolution lifecycleAPI reference
Use a credential in a native connectionaner.db and all four connectors, aner.llm, aner.api

Create references without reading credentials

The complete reference only program is runnable on every engine with aner.secrets:

aner
import aner.secrets

let stored = secrets.stored("example-service-key")
let environment = secrets.env("EXAMPLE_SERVICE_KEY")
let managed_file = secrets.file("example-service-key")
let project_file = secrets.dotenv(path: ".env.local", name: "EXAMPLE_SERVICE_KEY")
print(stored)
print(environment)
print(managed_file)
print(project_file)

Run aner check examples/secrets_references.aner, then aner examples/secrets_references.aner. Each line is an opaque SecretRef handle. No entry, environment variable or project file must exist: reference construction validates the name and any explicit path but reads no credential, writes no store and sends no request. A consumer resolves the selected reference later. The managed label and environment name here are fictional settings to replace deliberately.

Storage choices

ReferenceStorageAvailability and boundary
secrets.stored("openai")Operating system credential serviceNative macOS Keychain and Windows Credential Manager adapters are implemented. Linux system storage is unavailable.
secrets.env("OPENAI_API_KEY")Existing process environmentSupports deployment systems that inject credentials. Aner does not discover or load a .env file.
secrets.file("openai")Explicit managed Aner file storeAvailable on POSIX systems as a fallback. Windows uses its native system store. POSIX directories and files are owner only; values are plaintext on disk.
secrets.dotenv(path: ".env.local", name: "OPENROUTER_API_KEY")Explicit project environment fileReads one named key from exactly the selected file at consumer resolution. No environment mutation, discovery, merging or fallback. Plaintext on disk; native file access checks apply.

An environment variable is convenient for automation, but it is not an encrypted vault and may be inherited by child processes. The managed file store protects access permissions; it does not encrypt stored values. Operating system storage is a distinct choice with the platform service’s access policy. Native Windows support is implemented and has not yet been validated on a Windows host. System store behavior is subject to the local account and credential service policy; implementation availability is separate from host validation.

Set a credential with hidden input

Run the command in a local interactive terminal:

sh
aner secrets set openai

The command prompts for the value without echoing it. The default is --store system. Do not append a credential value to a command, paste it into source, or put it in a notebook cell. The command accepts a label; it does not accept a secret value as a command line argument. Automation may opt into --stdin to supply a value through standard input from its secret manager; interactive use keeps the hidden prompt.

Inspect configuration without displaying the value:

sh
aner secrets status openai

Remove the credential when it is no longer required:

sh
aner secrets delete openai

These commands manage Aner’s credential entry. Deleting an entry does not revoke the credential at its issuer; rotate or revoke it using that provider’s controls when needed. The credential name is a stable label that source can retain after the value changes. Managed labels contain at most 64 characters: letters, digits, underscores, periods, and hyphens, beginning with a letter or digit. Environment names contain at most 128 characters and follow identifier syntax. Credential values contain from 1 through 8192 visible ASCII bytes without whitespace or control characters.

Use a reference in Aner

aner
import aner.llm
import aner.secrets

let key = secrets.stored("openai")
let model = llm.client(provider: "openai", model: "gpt-4.1-mini", key: key)
let answer = model.generate("Explain the purpose of validation data.", max_tokens: 128)
print(answer.text())

Reference construction does not perform a provider request or return the credential value. The request resolves the reference through the selected store. Missing, empty, inaccessible, or invalid credentials produce a source located R3102 diagnostic; provider rejection produces a sanitized R3101 diagnostic. Credentials appear only in the native authorization path and are excluded from ordinary handle display and development inspection.

The same source can use an injected environment variable:

aner
import aner.secrets

let key = secrets.env("OPENAI_API_KEY")

Configure the process environment through the deployment system. secrets.env reads only that process environment; it does not read .env files. Use secrets.dotenv below to select a project file explicitly. Explicit environment references also support external secret managers without coupling source to their storage format.

For OpenRouter, configure aner secrets set openrouter and construct llm.client(provider: "openrouter", model: "openai/gpt-4.1-mini", key: secrets.stored("openrouter")). The model slug is illustrative and depends on availability and account access. An injected environment key requires the explicit reference secrets.env("OPENROUTER_API_KEY"); the provider does not discover it automatically. See the OpenRouter example, Aner notebook, and Jupyter notebook for switching models with a shared credential reference.

Anthropic and Google Gemini use the same opaque references: configure aner secrets set anthropic or aner secrets set gemini, then pass secrets.stored("anthropic") or secrets.stored("gemini") to the corresponding native client. Explicit injected environment names are ANTHROPIC_API_KEY and GEMINI_API_KEY. To choose a project file, use secrets.dotenv(path: ".env.local", name: "ANTHROPIC_API_KEY") or the Gemini key name; .env, .env.production and .env.development work through the same explicit path argument. No provider discovers keys or files automatically. See the Anthropic and Gemini examples. Reported token usage is numeric response metadata and never requires exporting a credential value.

The provider switching notebook keeps separate Anthropic, Gemini and OpenRouter references and prints input, output and total tokens for each call. Download the Aner format or Jupyter format. Its setup explicitly selects stored, injected environment or one private dotenv file; its three request cells never print a credential value. Running all cells sends three requests and can incur provider charges.

Explicit project environment files

secrets.dotenv requires Aner 0.0.4 or newer; see installation and availability.

Keep the private key in a local file excluded from version control, and reference it through aner.secrets:

aner
import aner.llm
import aner.secrets

let key = secrets.dotenv(path: ".env.local", name: "OPENROUTER_API_KEY")
let model = llm.client(provider: "openrouter", model: "openai/gpt-4.1-mini", key: key)

Select one exact path: .env, .env.production, .env.development, or .env.local are ordinary explicit choices. For example, change only path: ".env.local" to path: ".env.production" for the production file. Aner does not discover a file, merge multiple files, fall back to another file or an environment variable, or change the process environment. Relative paths are normalized to absolute paths against the native process working directory when the reference is constructed. This directory may differ from the notebook's folder; use an absolute path when needed. Construction does not open the file. Each authenticated LLM request resolves the same reference afresh, so later file updates apply to later requests.

Create the file privately in your editor and add the assignment OPENROUTER_API_KEY=YOUR_PRIVATE_KEY, replacing the placeholder locally. Keep actual credentials out of source, notebook cells, notebook output and Git history. On POSIX systems, set owner only permissions before using the file:

sh
chmod 600 .env.local

Exclude .env, .env.production, .env.development, and .env.local in the project's .gitignore. These are plaintext files. On POSIX, the selected file must be owned by the current user, have mode 0600, be a regular file with one link, and have no symbolic links in any path component. On Windows it must be a native regular file without a final reparse point; operating system access controls apply. Unsafe or unreadable files fail without exposing their contents.

The parser accepts single line NAME=value assignments, an optional export prefix, spaces or tabs around the name and value, literal single or double quotes, trailing # comments, LF or CRLF line endings, and an optional UTF-8 BOM. After an unquoted value, # starts a comment only when preceded by whitespace; otherwise it is literal. After a closing quote, a comment may follow directly. Quotes do not evaluate escapes or interpolate variables: values such as $OTHER_KEY stay literal. Multiline values are unsupported. Unrelated lines are ignored; a missing, duplicate or invalid target assignment fails with a sanitized credential diagnostic. The file is limited to 1 MiB, and the selected value must contain 1 through 8192 visible ASCII bytes without whitespace or control characters.

secrets.dotenv is a read only project file reference. The CLI's aner secrets set, status, and delete commands manage system or managed file entries, and do not edit or inspect project environment files. secrets.file("openrouter") continues to address Aner's managed store by label; it does not accept a project file path. Neither reference provides a raw value getter.

Headless Linux and the file fallback

A headless machine without a supported system store can opt into the managed file store:

sh
aner secrets set openai --store file
aner secrets status openai --store file

The matching source reference is explicit:

aner
import aner.secrets

let key = secrets.file("openai")

To remove the managed entry:

sh
aner secrets delete openai --store file

A file store label addresses a managed entry; it is not an arbitrary path. The default managed directory is .config/aner/secrets beneath the operating system account’s home directory. An explicit absolute ANER_SECRETS_DIR may select a separate private store for a container or isolated deployment; the same ownership, permission and symbolic link checks apply. It does not enable project file discovery. On POSIX systems the store directory must be owned by the current user with mode 0700, and credential files must be owned by that user with mode 0600. Unsafe ownership, permissions, or symbolic links are rejected. An isolated profile can be backed up or removed according to local policy; backups contain plaintext credentials and require the same care as the original store.

Explicit file storage is useful where an operating system vault is unavailable, but encrypted deployment storage or injected short lived credentials remain preferable when the environment provides them. Aner does not silently fall back from an unavailable system store to plaintext files.

API reference

CallResultResolution
secrets.stored(name: String)SecretRefManaged operating system credential entry.
secrets.env(name: String)SecretRefNamed variable in the current process environment.
secrets.file(name: String)SecretRefManaged owner only file entry.
secrets.dotenv(path: String, name: String)SecretRefOne named key in the explicitly selected project environment file.

All factories validate name immediately and return immutable references; they do not verify that the referenced credential exists. Managed labels have 1 through 64 ASCII characters and environment names for env and dotenv have 1 through 128, with the character rules above. dotenv also validates a nonempty path of at most 4096 bytes without control characters, normalizes it and retains the absolute path. Invalid factory inputs and LLM credential resolution failures use source located R3102. Native database and API consumers sanitize credential failures under their own R3401 and R3301 diagnostics respectively. aner check validates call shape/types without resolving a credential. Store availability is checked when a consumer or CLI command uses the chosen store; secrets.stored construction alone does not establish platform support.

SecretRef is an opaque native type. It has no raw value getter, implicit String conversion, serialization export, or method that prints the credential. A provider connection receives the reference and resolves it natively when needed. Current credential consumers are Language model connections, Model inference APIs, and Native database connections. Database factories resolve their password at connection time. An LLM client resolves its credential for each authenticated provider request. An API listener resolves its inbound bearer credential once at startup and retains the resolved value in private memory while running. Changing or deleting that store entry does not revoke the already running listener's token; stop or restart the listener to apply rotation or removal. A restarted listener must resolve a valid configured credential before accepting requests. Use a dedicated inbound API credential separate from an upstream provider credential.

Observation and transport

A reference protects the credential, not every piece of application data. Plain prompt Strings and generated text explicitly extracted through answer.text() remain ordinary values; printing or capturing them can retain content in reports or notebooks. Opaque message, client, and response handles hide their content during ordinary inspection. Saved notebook output is separate from credential storage and should be reviewed before sharing.

The LLM module uses verified HTTPS for nonlocal connections. It rejects credentials embedded in URLs, follows no redirects, and does not use ambient HTTP proxy variables. Local loopback HTTP supports local inference and explicitly established tunnels. An IP address on a private network is not a substitute for encryption. Credentials and provider error bodies are not copied into diagnostics.

Credential storage does not grant a provider permission to use a dataset. Select endpoints, account policies, and allowed data deliberately before making a request. Production mode disables development recording while retaining the same authenticated inference behavior.

Native database connections

aner.db.postgres, aner.db.mysql, aner.db.mssql and aner.db.mongodb consume SecretRef passwords when opening a connection. They accept the same stored, environment, managed file or explicit project environment file references; a password String is not accepted. An open native session keeps the authentication state needed for that connection. Changing a stored value applies when a new connection resolves the reference. Missing/inaccessible credentials and database failures produce sanitized R3401 diagnostics without native messages that might echo private configuration.

sh
aner secrets set example-postgres-password --store system
aner
import aner.db.postgres
import aner.secrets

let connection = postgres.connect(
    host: "postgres.example.invalid", port: 5432, database: "example_science",
    user: "example_reader", password: secrets.stored("example-postgres-password"),
    sslmode: "verify-full", timeout_seconds: 10)
db.close(connection)

These are fictional settings. See native databases and PostgreSQL connection guidance for verified TLS, private CA configuration, typed results and examples. The other database guides document backend specific native dependencies and their document/SQL APIs.

Time and space complexity

For a credential name of n bytes, constructing a SecretRef takes O(n) time and O(n) retained space. An explicit dotenv path of p bytes adds O(p) time and retained space. Name, path and credential size validation use bounded inputs. Environment resolution reads the selected value; managed file resolution reads bounded stored bytes; dotenv resolution scans O(f) bounded file bytes with O(f) temporary space; system store resolution is governed by the operating system service. No universal latency bound is assigned to an external credential service. Secret values are not part of the returned Aner object.

See the complete callable index for the native module and method name catalogue.

Aner documentation · Reference and guides