Import personal access tokens with auth login --with-token

Merged
JE
3mo ago
+2640-139

⚠️ Release note — paste into the release description at release prep

basecamp auth login --with-token imports a personal access token. Pipe a
token from a secret store — never as an argument — and it is stored under a
named profile with whatever expiry the server reports, creating the profile when
--account names its account:
op read "op://Vault/Item/credential" | basecamp auth login --with-token -P bot --account 999.
The token is verified against the server before anything is kept.

Every login can now assert who it signed in as. --expect-identity <id>
discards the new credential (restoring a profile's previous one) and exits
non-zero when the server reports a different identity — browser, device, and
token imports alike. --json on a token import returns the envelope with the
profile, account, identity, person, oauth_type, scope, and expires_at (the server-reported expiry, or null).

Interactive logins refuse machine output modes. basecamp auth login --json
(or --agent, --quiet, …) used to print prose and block for minutes on
approval; it now exits immediately with a usage error pointing at
auth status and --with-token. A configured format: json is unaffected.

BASECAMP_OAUTH_ISSUER pins the OAuth authorization server for the
production dark pilot and will be removed once the server advertises its
metadata. --login-hint <email> is sent with the device authorization request
to steer the approval page's sign-in (Launchpad ignores it). Release notes are
GitHub-native and carry only the PR title, so this paragraph has to be added by hand.

A bot's Basecamp identity should never come from a browser sign-in on a shared machine: whoever's session the browser holds is who the profile quietly becomes, and nothing checks. Basecamp now mints personal access tokens (bc_at_…, revocable, full/read scope), so the CLI can take one from a secret store and refuse to keep it unless it authenticates as the expected identity. This is the CLI half of the Clawdito setup work in basecamp/coworker; the operator-facing flow is

op read "op://coworker-agent-clawdito/37s Basecamp PAT - Clawdito/credential" \
  | basecamp auth login --with-token -P clawdito --account 2914079 --expect-identity 28142355

What

--with-token (internal/commands/auth.go)

  • Reads the token from stdin, trimmed; a terminal stdin is refused with the op read "op://…" | basecamp auth login --with-token -P <profile> --account <id> shape. Empty, multi-line, whitespace-bearing, control-character-bearing, or >4 KiB input is rejected without echoing it. The token is never written to output or errors.
  • Requires a named profile (-P/--profile or BASECAMP_PROFILE; a single/default profile resolves too). When the profile does not exist, --account <id> is required and the profile is created with the current base URL. An existing profile keeps its entry untouched; passing an --account that differs from the profile's binding is a usage error rather than a silent rebind.
  • Verifies before it persists. The candidate token gets a client of its own (App.SDKClientFor(StaticTokenProvider) — same transport, hooks and user agent as the real client) and must pass three checks before anything is written: the authorization document answers for it (identity id, email, reported scope — anything but read/full is refused); the effective account (--account / BASECAMP_ACCOUNT_ID override the profile binding at runtime, so that is what is compared; a new profile must get its account explicitly, not from the operator's config file; digits only) appears non-expired in that document; and the account-scoped person lookup ForAccount(acct).People().Me succeeds. Only then auth.Manager.ImportToken stores {AccessToken, OAuthType: bc5, Scope, UserID, UserEmail} in one write and the profile is registered. A rejected token touches neither the store nor config.json, and a profile's previous credential is never read or written. The server-reported expiry is stored with it (ExpiresAt 0 when none is reported, the path AccessToken never refreshes); near a reported expiry the token is refused with "No refresh token available" and must be imported again.
  • Production serves /my/profile.json only under an account prefix (verified live: unscoped → 404, /2914079/my/profile.json → 200), which is why the person lookup is account-scoped. The pre-existing "Logged in as" step in login/profile create used the unscoped path and had been failing silently.
  • BASECAMP_TOKEN in the environment is refused up front for --with-token and --expect-identity, since every request would otherwise carry it instead of the credential being checked.
  • Profile registration is factored out of profile create into registerProfile/unregisterProfile (profile.go), used by create, delete, and the import. The root pre-run gains an AnnotationProfileMayCreate carve-out so -P <new-name> reaches the command instead of failing with "unknown profile"; an unregistered name is not used as a cache-path component.

--expect-identity <id> — the same verifier runs inside the browser and device flows through a new auth.LoginOptions.Verify hook, called with the freshly issued token before store.Save. A mismatch stores nothing, prints no success line, and exits 3 (auth); a pre-existing credential is untouched. Without an expectation the "Logged in as" line stays best-effort. Output: Logged in as Clawdito <clawdito@…> (identity 28142355, person 51177542) (server-supplied name/email reduced to one line for the terminal; JSON verbatim).

--json — envelope for the import: profile, account_id, base_url, source: "token", oauth_type: "bc5", scope, expires_at: null, identity: {id, email}, person: {id, name, email}, profile_created, default. Interactive flows under --json/--agent/--quiet/--ids-only/--count now refuse before any network call (the machine-mode half of #669; BASECAMP_NONINTERACTIVE is deliberately not gated — a device login prints instructions and waits on a browser, not on stdin, which is a valid headless shape).

BASECAMP_OAUTH_ISSUER (internal/auth/auth.go) — when set, discoverOAuth skips discovery and builds oauth.Config{TokenEndpoint: issuer+"/oauth/tokens", DeviceAuthorizationEndpoint: issuer+"/oauth/device_authorizations"} (the paths bc3 mounts). The value passes the same isSecureEndpointURL checks as a discovered endpoint plus a no-query/no-fragment rule, is never echoed, and never falls back to Launchpad. Documented in the README as the dark-pilot escape hatch to remove after go-live.

--login-hint <email> — threaded through LoginOptions.LoginHint and sent by the device flow as Basecamp's login_hint extension via oauth.WithDeviceLoginHint (basecamp/basecamp-sdk#841, merged as 47e7ca38). The option is appended only when a hint was given, so an unqualified login's form is unchanged; Launchpad logs that it ignores the flag. The SDK is bumped with make bump-sdk REF=main (v0.15.0 → v0.16.1-0.20260903193203-47e7ca381a49, provenance updated, catalog parity tests green); the bump also carries the SDK's own 0.16.0 additions (to-do list template library, recent projects, spotlight), for which the CLI commands and API-COVERAGE rows are a separate SDK-sync task, not this PR.

Usage

op read "op://<vault>/<item>/credential" | basecamp auth login --with-token -P bot --account 999
op read "op://<vault>/<item>/credential" | basecamp auth login --with-token -P bot --account 999 --expect-identity 12345 --json
basecamp auth login --expect-identity 12345
basecamp auth login --device-code --login-hint bot@example.com
BASECAMP_OAUTH_ISSUER=https://app.basecamp.com basecamp auth login --device-code -P scratch

Verification

  • go build ./..., go vet ./... — clean.
  • go test ./internal/auth ./internal/commands ./internal/cli ./internal/stdinarg — green. New coverage: token import happy path through a real httptest identity server (trailing newline trimmed before the Authorization header; stored ExpiresAt 0; AccessToken serves it with no refresh); --json envelope shape; --expect-identity mismatch deletes the credential and registers no profile; mismatch on a pre-existing profile restores its previous credential byte-for-byte; unverifiable identity fails closed only with an expectation; a server-rejected token is not kept; server-reported scope wins; missing --account, missing profile, account mismatch, existing profile's entry (project_id, default_profile) untouched; bad stdin matrix (empty, whitespace, two lines, inner space, control char, oversized) with no echo; terminal stdin refusal (PTY); BASECAMP_TOKEN refusal; non-numeric identity; flag exclusivity; machine-mode refusal matrix; unknown profile without --with-token. internal/auth: pinned issuer skips discovery (0 hits on the resource server) and stores the trimmed /oauth/tokens endpoint; rejected issuer matrix (plain http, userinfo, no host, bad port, file scheme, query, fragment) never echoes and never falls back; login hint sent on the device flow (since round 9) and ignored on Launchpad; ImportToken round trip and refresh behavior. internal/cli: may-create pass-through for --profile and BASECAMP_PROFILE, refusal otherwise. internal/stdinarg: IsTerminal over buffer, pipe, /dev/null, PTY.
  • make fmt-check vet check-surface check-skill-drift check-bare-groups tidy-check — green; .surface regenerated with the six new flag entries (auth login and the login shortcut).
  • make test-e2e — green, including four new auth.bats cases (help text, profile required, --account required, --with-token excludes --device-code).
  • bin/ci green on Linux/x86 (thelio, Go 1.26.7) at a2defe8: fmt, vet, lint (0 issues), unit tests, 446 e2e, naming, surface, skill drift, bare groups, lint lockstep, smoke coverage, provenance, tidy. The PTY-class tests (TestIsTerminal, TestAuthLoginWithTokenRefusesTerminalStdin, TestInteractiveStdio, TestIsInteractiveTTY…, …) pass there; on this Mac's sandbox they fail identically on main because /dev/ptmx is not a terminal, and its golangci-lint predates the Go 1.27 export-data format, so Linux is the reference run.
  • Review round (14c33b8): verify-before-persist replaces the snapshot/restore; account verification (authorization document + account-scoped person lookup, env-override and non-numeric cases tested); --scope/--expect-identity validated before stdin is consumed (a test asserts stdin is left unread); device-flow --expect-identity mismatch stores nothing and prints no success line (end-to-end through a pinned issuer serving the grant); sanitization tests for the login hint, the pinned issuer (U+0085) and a server-supplied name (OSC hyperlink + CRLF); unregistered profile name kept out of the cache path (--profile ../../outside); e2e cases assert exact .error/.code under env -u BASECAMP_PROFILE; doctor skill carries the token-import and --expect-identity remediation.
  • Review round 3 (a2e8a69): an existing profile's base URL must match the effective one and an unbound profile is bound to the explicitly given account (entry otherwise preserved); account comparisons numeric; profile entry written before the credential (no orphaned secret); strict mode refuses a document with no identity id; non-strict logins keep the authorization identity when the account/person lookup fails and never write user_id 0; stdin accepts exactly one trailing LF/CRLF.
  • Review round 4 (a2defe8): the server-reported expiry is stored and reported (null when absent; near expiry the token is refused with the existing no-refresh-token error); Args: cobra.NoArgs; binding an accountless profile defined outside the global config is refused before stdin.
  • Review round 6 (709798b): global config writers refuse a malformed file instead of rewriting a partial decode; the near-expiry refusal is import-only (an asserted OAuth login keeps its refresh token); imported credentials carry source: "token", reported by auth status and profile show.
  • Review round 7 (283c4f9): BASECAMP_OAUTH_ISSUER accepts an origin only; global config writers refuse a non-object profiles value and create the config directory first; README names app.basecamp.com.
  • Review round 8 (45bc77b): profile create proves the global config can take an entry before running OAuth (no credential left without a profile on a malformed file); README stops calling an imported token non-expiring.
  • Review round 9 (313c5b0): SDK bumped to main and --login-hint sent on the wire (TestLoginDevice_LoginHintIsSent asserts the form carries login_hint, and omits it when no hint is given). No review fixes this round: six threads left open on purpose — three server-reflected-bearer findings declined on merit, two config-file-hardening and one OAuth-binding finding flagged for Jeremy as the third-plus variation of settled classes.
  • Review round 10 (73da0c7; first pushed as d33707a): origin/main merged (78e1a65; go.mod keeps the SDK pin, main's goldmark bump preserved, go mod tidy) and main's new TestCatalogModelProvenance satisfied by recording the pinned revision in the MCP model provenance (model files byte-identical to v0.16.0). Fixes: a bare trailing CR on stdin is refused (e26b374); a top-level null config is refused instead of panicking, the import preflights the config file before reading stdin, and profile delete preflights it before the credential goes (362cc81); the profile-binding check is one helper run by every login that names an existing profile, OAuth flows included (50b4fe8); profile create --expect-identity runs the same verifier, and the account-scoped person lookup replaces the unscoped /my/profile.json fetch (d33707a). The SDK-sync thread is overtaken by main's own v0.16.0 sync. Still open on purpose: the three server-reflected-bearer threads, declined on merit as before.
  • Round 10 follow-ups (35bda36 → 73da0c7): unparam on the config preflight (da5db35); grpc v1.83.2 for CVE-2026-84445, an indirect dep main shares whose advisory started failing the Trivy scan (35bda36); a bare ?/# on BASECAMP_OAUTH_ISSUER is refused on the raw value — url.Parse reports an empty fragment as absent while the concatenated endpoints carried it (a81be7c); the import's terminal line says "no expiry reported" (071a546); the preflight is renamed globalConfigTakesProfiles for what it checks (fffcde5); Nix vendorHash recomputed and verified via make update-nix-hash (73da0c7). Declined: a permission probe / two-store rollback for the config preflight (two Copilot threads, left open with reasoning) — sixth variation of the config-file series. Copilot resolved the three server-reflected-bearer threads itself on re-review. bin/ci green on thelio at 73da0c7; GitHub CI green.
  • SDK pin: no basecamp-sdk tag after v0.16.0 includes #841 (gh release list shows v0.16.0 as latest), so the pseudo-version v0.16.1-0.20260903193203-47e7ca381a49 stays. Tagging sdk v0.16.1 and running make bump-sdk REF=v0.16.1 + scripts/sync-mcp-model.sh would restore the tagged shape in both provenance files.
  • Not run live: the production import (op-coworker read clawdito … | basecamp auth login --with-token -P clawdito --account 2914079 --expect-identity 28142355) and BASECAMP_OAUTH_ISSUER=https://app.basecamp.com basecamp auth login --device-code wait on the bc3 pilot deploy (work package A/B).

Not doing here

  • Gating interactive login on BASECAMP_NONINTERACTIVE (the other half of #669) — see above.
  • Any new credential store: the token lives in the existing keyring/file store under profile:<name>.

Summary by cubic

Adds basecamp auth login --with-token to import a personal access token from piped stdin and verify it for the requested account and identity. Unlike browser login, which could silently use the browser’s current identity, --expect-identity now protects OAuth and profile create too, leaving existing credentials untouched on failure.

Authentication

  • New profiles require a named profile and explicit --account; existing profiles reject account or base-URL mismatches.
  • Token input must be a single non-terminal value, is never echoed, and cannot come from an argument or BASECAMP_TOKEN.
  • Verification checks the token’s identity, account, scope, person, and expiry before storing it.
  • Imported credentials record source: "token" plus the server-reported scope and expiry; auth status, profile show, and --json expose them.
  • Tokens without refresh support are refused near expiry and must be imported again.
  • Interactive logins reject machine-output flags before network calls, while --login-hint is sent with device authorization.
  • BASECAMP_OAUTH_ISSUER now accepts only a valid origin without a path, query, or fragment.

Configuration and dependencies

  • Profile registration and global config writers validate malformed or non-object config, create missing directories, and preflight writes before authentication changes state.
  • OAuth and token logins share profile-binding checks, and account-scoped person lookup replaces the failing unscoped lookup.
  • Updates github.com/basecamp/basecamp-sdk/go for device login hints and google.golang.org/grpc to v1.83.2 for CVE-2026-84445.