From 44efdd76e7e2adb7d4fbaa36712da1a66a698a14 Mon Sep 17 00:00:00 2001 From: Youness Aamiri <41025072+AamiriYouness@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:05:23 +0000 Subject: [PATCH] docs: accept ADR 0011 (protected storage) and the .NET 11 toolchain ADR 0011: session files stay files but are AES-256-GCM encrypted, with one random key per store directory in the macOS Keychain (creator-only access), protected by DPAPI on Windows, or in the Linux Secret Service. File leases and atomic writes move to Shared.Storage and are reused. A key is replaced only when definitively missing; an unavailable keyring fails with StorageUnavailable and never falls back to plaintext. Keyring calls have deadlines, and a probe lets hosts explain a missing keyring. ADR 0003 amendment: build with the .NET 11 SDK, target net10.0 and net11.0, and use C# 15. --- docs/ROADMAP.md | 43 ++-- .../0003-protocol-dependency-selection.md | 14 ++ docs/decisions/0011-protected-storage.md | 187 ++++++++++++++++++ 3 files changed, 224 insertions(+), 20 deletions(-) create mode 100644 docs/decisions/0011-protected-storage.md diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 4806321..fc5e988 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -29,17 +29,19 @@ HTTP and DI layer, then the first preview. and 42306759178). The providers workflow runs nightly and on push to main, requiring `Auth0,Entra`. Okta is paused and no longer blocks later milestones. Google and GitHub are dropped ([ADR 0010](decisions/0010-provider-compatibility.md) section 5). -- Active: re-plan on branch `roadmap/keyring-first`. Roadmap reordered, Google and - GitHub removed from the compatibility tables, ADR 0010 section 5 added. The unpushed - Google branch `milestone-2/phase-5-google` (Core commits `233066b` installed-app secret - and `5d73544` `verification_url` fallback) is abandoned, not merged; its uncommitted - test code and guide are in a local stash. CI trimmed on the same branch: the - fixture helper build, format check, and AOT analysis run on Linux only; tests and the - native AOT publish and smoke still run on Ubuntu, Windows, and macOS under the same - required job names. -- **Next action:** merge the re-plan PR, then start milestone 3: draft the protected - storage ADR (see milestone 3, "Decide first") and discuss it with the maintainer - before any code. +- Done: re-plan (PR #14, branch `roadmap/keyring-first`): roadmap reordered, Google and + GitHub removed from the compatibility tables, ADR 0010 section 5, and OS-independent CI + steps on Linux only. The unpushed Google branch `milestone-2/phase-5-google` is + abandoned, not merged; its uncommitted test code and guide are in a local stash. +- Active: milestone 3 (protected storage). The maintainer chose encrypted session files + with one OS-protected key per store directory, creator-only Keychain access, and + libraries targeting `net10.0;net11.0` with C# 15. Accepted on 2026-12-02: + [ADR 0011](decisions/0011-protected-storage.md) and the toolchain amendment to + [ADR 0003](decisions/0003-protocol-dependency-selection.md). The task-by-task + implementation plan is internal: it lives in the parent workspace, outside Git. +- **Next action:** the maintainer installs the .NET 11 SDK locally; then the toolchain + step (SDK 11, both target frameworks, C# 15, both runtimes in CI) on a branch cut from + `main` once PR #14 and this design branch are merged. ## Rules for every milestone @@ -196,15 +198,16 @@ Keep tokens in the OS keyring by default, as `gh` and `az` do. Plaintext files s explicit, clearly labeled opt-in. A team's security review is unlikely to accept a CLI that writes refresh tokens to plaintext files, so this comes before the first preview. -Decide first, in a new ADR: -- Native services: macOS Keychain, Windows Credential Manager (with DPAPI), and Linux - Secret Service. -- Headless Linux. SSH sessions and containers often have no Secret Service, which ops - users hit at once. Decide what happens there: an actionable error that names the - explicit plaintext option, never a silent fallback. -- Record size limits (Windows credentials are small), key naming, and what logout - removes. -- How cross-process leases work with a keyring backend (Shared.Storage). +Decided in [ADR 0011](decisions/0011-protected-storage.md): encrypted session +files reusing the file store, with one random key per store directory in the macOS +Keychain, protected by DPAPI on Windows, or in the Linux Secret Service. It also settles: +- Headless Linux (SSH sessions, containers without a Secret Service): an availability + probe and `StorageUnavailable`, so the host can name the explicit plaintext option; + never a silent fallback. +- Size limits avoided (only a 32-byte key leaves the file), key naming by random key id, + key loss (records read as corrupt; logging in again recovers), and what logout removes. +- Leases: the file store's leases and atomic writes move to `Shared.Storage` and are reused. +- Toolchain first: .NET 11 SDK, libraries on `net10.0;net11.0`, C# 15 (ADR 0003 amendment). - Implement the platform storage packages behind the existing `ITokenStore` contract. - Test against the real keyring on each OS in hosted CI. diff --git a/docs/decisions/0003-protocol-dependency-selection.md b/docs/decisions/0003-protocol-dependency-selection.md index 324f0ce..a7a1a5c 100644 --- a/docs/decisions/0003-protocol-dependency-selection.md +++ b/docs/decisions/0003-protocol-dependency-selection.md @@ -88,3 +88,17 @@ Accepted after joint review of the feasibility evidence and explicit maintainer approval. Retain the runnable spikes as supporting evidence and an upgrade baseline. Core contracts, internal adapters, complete flow tests, and the real-provider fixture remain implementation work; this ADR does not certify the package as production ready. + +## Amendment: toolchain, .NET 11 and C# 15 (accepted 2026-12-02) + +.NET 11 and C# 15 shipped on 2026-11-10. .NET 11 is a Standard Term Support release; .NET 10 is the +current Long Term Support release. Both are supported until November 2028. Teams building CLIs often stay +on LTS, so a package that targets only `net11.0` would exclude them. + +- Build with the .NET 11 SDK (`global.json`, latest patch, no prerelease). +- Libraries target `net10.0;net11.0`. Test projects target both too, so the `net10.0` build is tested, + not only compiled. The sample and test helper processes target `net11.0`. +- `LangVersion` 15 for every target. C# 15 features that need .NET 11 runtime or library types are used + only where they also compile for `net10.0`, or not at all; a feature never forks behaviour by target. +- Native AOT analysis covers both targets; the AOT-published sample uses `net11.0`. +- Lock files are regenerated once for the new targets. No package dependency changes as part of this. diff --git a/docs/decisions/0011-protected-storage.md b/docs/decisions/0011-protected-storage.md new file mode 100644 index 0000000..40a9b0a --- /dev/null +++ b/docs/decisions/0011-protected-storage.md @@ -0,0 +1,187 @@ +# 0011: Protected storage: encrypted session files with an OS-protected key + +Status: Accepted (2026-12-02; maintainer choices: encrypted files, creator-only Keychain access) + +Date: 2026-12-02 (roadmap milestone 3) + +## Context + +ADR 0005 shipped explicitly selected plaintext files first and left protected storage open: direct +native credential stores versus encrypted envelopes, key provisioning, loss and recovery, migration, and +runtime support. The 2026-12-02 re-plan moved protected storage ahead of the HTTP layer and the first +preview: the library aims at gh/az-style login for team and ops CLIs, and a CLI that keeps refresh tokens +in plaintext files is unlikely to pass a team's security review. + +What already exists and must keep working: + +- `ITokenStore` and `ISessionLockProvider` in Core; `PersistenceMode.Protected` is already the + `OidcProfile` default and part of session-key derivation. +- `FileTokenStore` (plaintext): bounded reads, staged and flushed writes with atomic replacement (native + publication on Windows), logout by deletion, orphaned staging cleanup, private-location checks + (ADR 0008), and cross-process leases (ADR 0006), all tested on Ubuntu, Windows, and macOS, including + process races. +- The coordinator treats an unreadable record as `StorageCorrupt`; explicit login may replace a corrupt + record and logout removes it (ADRs 0007, 0008). +- Package rules: platform storage packages reference Core only, never one another; Core and Extensions + never reference a backend; shared storage internals are source (`Shared.Storage`), not a package. + +Two designs were compared with the maintainer (see Alternatives). The maintainer chose encrypted files. + +## Decision + +### Shape + +Each session stays one file in a host-selected directory, as with the plaintext store, but its contents +are encrypted. Only one small random key per store directory lives in OS-protected storage. Everything +that makes the file store correct (atomic replacement, leases, location checks, logout, orphan cleanup) +is reused unchanged. + +### Packages and public API + +- `Bijecta.CliAuth.Storage.MacOS`: `KeychainTokenStore`, key in the user's login keychain. +- `Bijecta.CliAuth.Storage.Windows`: `DpapiTokenStore`, key protected with DPAPI for the current user. +- `Bijecta.CliAuth.Storage.Linux`: `SecretServiceTokenStore`, key in the Secret Service (libsecret). + +Each is a public sealed class implementing `ITokenStore` and `ISessionLockProvider`, declares +`PersistenceMode.Protected` without I/O, and takes an absolute storage directory like `FileTokenStore`. +Each is marked `[SupportedOSPlatform]` for its OS, so the platform analyzer flags misuse at build time; +constructing one on another OS throws `CliAuthException(StorageUnavailable)`. Selection stays explicit +and two-sided (ADR 0008): the profile requires `Protected`, the host passes one of these stores. Nothing +selects a backend by OS, and there is no fallback to plaintext. + +Each store also has a static availability probe, `ProbeAsync(CancellationToken)`, returning Core's new +`ProtectedStoreAvailability` enum (`Available`, `ServiceMissing` for a missing library or Secret Service, +`NoSession` for no session bus or no user keychain, `Locked`, `Refused`). It takes no directory, reads and +writes no session or key, never prompts, and finishes within the keyring deadline below. On Windows it +returns `Available` unless DPAPI fails a protect/unprotect round trip of throwaway bytes. It lets a host +decide up front and tell the user what to do, such as "no keyring on this machine: pass +`--storage plaintext` to store tokens unencrypted". Choosing plaintext after a failed probe is the host's +explicit decision, not a library fallback. The enum lives in Core because it is provider- and +platform-neutral and the three packages share it. + +### Shared code + +The file machinery moves from `Bijecta.CliAuth.Storage.File/Internal` into `Shared.Storage` and is +compiled into the File package and each platform package: location checks, leases (`UnixSessionLock`, +Windows locking), Windows publication, staging and orphan cleanup, and the session JSON serializer. A +shared internal record store reads and writes opaque bytes with today's guarantees; a codec turns a +`StoredSession` into those bytes: plaintext JSON for the File store, encrypted JSON for protected stores. +The plaintext store's file names, format, and behaviour do not change; its existing tests guard the move. + +### File format + +- One file per session, `.session`, beside the existing `.lock` files. Plaintext stores keep + `.json`, so the two never read each other's records. +- Contents: a fixed header (magic `BCAP`, format version byte `1`, 12-byte random nonce), then the + AES-256-GCM ciphertext of the existing session JSON, then the 16-byte tag. +- Associated data: `Bijecta.CliAuth.Protected/v1`, the format version, the key id, and the session key. + A record copied to another session's file name or another store fails authentication. +- A fresh random nonce for every write. One key encrypts few records, far below GCM's random-nonce limits. +- The existing 1 MiB read bound applies to the whole file. +- `System.Security.Cryptography.AesGcm`. Its support on all three OSes is the first thing tested. + +### Key lifecycle + +- A store directory holds `store.json` (unencrypted, private file): format version and a random 128-bit + key id. The OS keyring entry is named by service `Bijecta.CliAuth` and that key id, so names reveal no + user, profile, or path, and moving the directory keeps working. +- The key is 32 random bytes, created on the first write under a store-wide lease (the existing lease + provider, on a fixed lock name), so two processes never create two keys. Reads never create a key. +- Every key lookup has three outcomes: **found**, **definitively not found**, or **unavailable**. + Not found means the OS said so (`errSecItemNotFound`; a libsecret lookup returning no secret and no + error; no `store.key` on Windows). Locked, refused, no session bus, a missing library, a timeout, or any + other failure is unavailable. +- A new key and key id are created, under the store-wide lease, only when `store.json` is missing or + unreadable, or its key is definitively not found (keyring reset, new machine, copied directory). + Unavailable never creates a key: the operation fails with `StorageUnavailable`, so a locked keyring or + an SSH session cannot invalidate a store's sessions. +- Records encrypted under another key, or that fail authentication with the current key, read as + `StorageCorrupt`; that never replaces the key. Existing behaviour then applies: status and token + acquisition report `StorageCorrupt`, explicit login replaces the record under the current key, and + logout removes it. Nothing is lost that a login does not restore. +- When a key is replaced and the old key id is known, the old keyring entry is deleted (best effort), so + replacements leave no orphans. Logout removes records, never the key. No scheduled key rotation in this + milestone; a later method may delete a store's key and records together. + +### Platform key storage + +- **macOS:** a generic password item in the default (login) keychain through Security.framework + (`SecItemAdd`, `SecItemCopyMatching`, `SecItemUpdate`, `SecItemDelete`) with `LibraryImport`. The + data-protection keychain needs entitlements a CLI does not have. The item keeps the default access + control (maintainer decision, 2026-12-02): only the creating program reads it silently. A CLI signed + with a stable identity keeps silent access across updates. An unsigned CLI gets the system "allow + access" dialog after each update; in a session without a GUI (SSH, CI) the read fails at once with + `errSecInteractionNotAllowed`, which is `StorageUnavailable`, until the user approves at the Mac. The + usage docs tell teams to sign their CLI and explain the dialog. +- **Windows:** the key is stored in the store directory as `store.key`, encrypted with DPAPI + (`CryptProtectData`/`CryptUnprotectData`, current user, `CRYPTPROTECT_UI_FORBIDDEN`) through + `LibraryImport`. DPAPI works without an interactive logon session, unlike Credential Manager over SSH. + The file gets the same private ACL checks as session files. +- **Linux:** the key is stored through libsecret (`libsecret-1.so.0`) with its non-variadic `v` + functions (`secret_password_storev_sync`, `secret_password_lookupv_sync`, `secret_password_clearv_sync`) + and a fixed schema, through `LibraryImport`. A missing library, no D-Bus session bus, or a locked + collection that cannot prompt is `StorageUnavailable`, never a fallback. Servers and containers + without a Secret Service therefore need the explicit plaintext store, and the docs say so. + +### Deadlines and threads + +Native keyring calls never show library-initiated UI where the API allows forbidding it (DPAPI with +`CRYPTPROTECT_UI_FORBIDDEN`; no libsecret unlock prompt). The one exception is the macOS "allow access" +dialog described above, which is how a user re-grants access after an unsigned update. Each call runs off +the caller's thread and honours the operation's cancellation token, with a deadline of 10 seconds, or 60 +seconds for a macOS keychain read that may be waiting on that dialog: libsecret calls get a `GCancellable` +that is cancelled on either; a macOS call that outlives its deadline is abandoned and reported as +unavailable. A stuck keyring therefore fails with `StorageUnavailable` instead of holding a session lease +indefinitely and leaving other processes with `SessionBusy`. The resolved key is cached per store +instance, so most operations make no keyring call. + +### Errors + +No new `AuthErrorCode`. A missing or refused keyring is `StorageUnavailable`; an undecryptable record is +`StorageCorrupt`; an unsafe location is `StorageInsecure`. Hosts that need the reason use the probe. +Native error details stay internal, as with Windows publication today. + +### Migration + +Moving from plaintext to protected storage is a new store and a new session key (ADR 0008), so users log +in once. The library does not copy plaintext tokens into protected storage. A host may remove the old +plaintext records with logout. + +### Testing + +- Test first: crypto and format tests (round trip, tampering, wrong key, wrong session key, truncation, + oversize, nonce uniqueness) and key-lifecycle tests (create once under concurrency, key loss reads as + corrupt, next write rotates the key id) against a fake key protector, on every OS. +- One store conformance suite, run against the plaintext store, each protected store with the fake key + protector, and each protected store with its real keyring on its own OS. +- Real keyrings in hosted CI: Windows DPAPI as the runner user; a temporary unlocked keychain on macOS, + created and set as default in a setup step; on Ubuntu, `gnome-keyring` and `libsecret-1-0` installed and + the test step run under `dbus-run-session` with an unlocked `gnome-keyring-daemon`. Real-keyring tests + carry a `Keyring` trait and skip when their OS's keyring is absent locally, but fail in CI + (`CLIAUTH_REQUIRE_KEYRING=1`), like the provider tests' required list. These steps go inside the + existing required jobs; their names do not change. +- The cross-process race tests also run against the protected store for the host OS. +- The Native AOT smoke test logs out, lists, and checks `token` against a protected store on each OS. + +## Consequences + +- The plaintext store and its tests stay as they are, after a source move into `Shared.Storage`. +- Three platform packages gain real code, marked by OS, with native calls through `LibraryImport` only. +- Copying a protected store directory to another machine or user exposes nothing: its key does not come + along. A process running as the same user can still read the key, as ADR 0005's threat model already + accepts. +- On Windows the key file sits beside the records; DPAPI, not the directory, is what protects it. +- The sample uses protected storage by default and plaintext only with an explicit flag. + +## Alternatives considered + +- **Tokens directly in the keyring, one item per session (the gh approach).** Rejected: file leases + would no longer cover the data, so each OS needs a new locking design; Windows credentials hold about + 2.5 KB, smaller than some Entra token sets, so records would need chunking; session listing and logout + would differ per OS. +- **Credential Manager for the Windows key.** Rejected for now: it needs an interactive logon session + and fails over SSH, which ops users rely on. DPAPI covers the same user boundary. +- **Talking D-Bus directly on Linux (for example Tmds.DBus.Protocol).** Rejected for now: it would + reimplement the Secret Service session protocol. libsecret is present wherever a Secret Service runs. +- **Deriving the key from a user passphrase.** Rejected: it prompts, which breaks silent token + acquisition and scripts.