From 2b1045c0ad829aca28d0f56c7f2868c075e2f247 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sun, 26 Jul 2026 14:49:32 +1000 Subject: [PATCH] feat: secrets-engine registry with yaegi extension interface (archie-core-xec) Adds internal/secret: a pluggable Engine interface (Name/Version/Resolve) resolved through a Registry, so secrets backends (sops, Bitwarden Secrets Manager, Vault/OpenBao) aren't hard-coded into the binary. Only the "env" engine is compiled in; custom engines are Yaegi-interpreted .go plugins loaded via Registry.LoadDir, mirroring internal/plugin's conventions (secretextract provides the generated, nil-guarded symbol table for the Yaegi/Go interface boundary). config.Forge.TokenEnv is replaced end-to-end with config.Forge.Token (secret.SecretRef{Engine, Key}) -- finalize() defaulting, forge token resolution in cmd/archied/main.go, and per-identity validation that now requires an explicit token instead of silently resolving to "". No backwards-compat shim. Provider.APIKeyEnv, NATSConfig.TokenEnv, and TelegramConfig.TokenEnv are deliberately not migrated here -- they're forwarded by name to ai-sdk/runtime and subprocess workers rather than resolved centrally, which needs its own eager-resolve-then-inject design pass (archie-core-xec.4). The three shipped engine plugins (sops, bws, vault/openbao) are tracked separately as archie-core-xec.1-3. Adversarially reviewed by a fresh agent with no implementation context; fixed the two findings that survived (missing per-identity token validation, underdocumented nil-wrapper Resolve edge case). --- .beads/interactions.jsonl | 2 + .beads/issues.jsonl | 7 +- ARCHITECTURE.md | 4 +- cmd/archied/main.go | 10 +- config.example.toml | 8 +- internal/config/config.go | 14 +- internal/config/config_test.go | 57 ++- internal/config/feature_config_test.go | 30 +- internal/daemon/daemon_test.go | 5 +- internal/secret/engine.go | 72 +++- internal/secret/loaddir_test.go | 358 ++++++++++++++++++ internal/secret/secret.go | 33 +- internal/secret/secret_test.go | 24 -- ...amcharles93-archie-core-internal-secret.go | 54 +++ .../secret/secretextract/secretextract.go | 16 + .../secretextract/secretextract_test.go | 59 +++ 16 files changed, 639 insertions(+), 114 deletions(-) create mode 100644 internal/secret/loaddir_test.go create mode 100644 internal/secret/secretextract/github_com-samcharles93-archie-core-internal-secret.go create mode 100644 internal/secret/secretextract/secretextract.go create mode 100644 internal/secret/secretextract/secretextract_test.go diff --git a/.beads/interactions.jsonl b/.beads/interactions.jsonl index 2a5790973..c69f5a2ee 100644 --- a/.beads/interactions.jsonl +++ b/.beads/interactions.jsonl @@ -115,3 +115,5 @@ {"id":"int-7fd486a1d4525ef2785aaea7473f39ef","kind":"field_change","created_at":"2026-07-26T00:39:59.583793112Z","actor":"Sam Catlow","issue_id":"archie-core-abg.34","extra":{"field":"status","new_value":"closed","old_value":"open","reason":"Persona registry implemented. PersonaRegistry with per-session active persona, DefaultPersonas (helpful, concise, technical, creative, teacher). Persona prompt injected into system prompt before memory context. 5 tests."}} {"id":"int-d5928c0fb2a8a61739a144f143c08eb8","kind":"field_change","created_at":"2026-07-26T03:56:19.96387364Z","actor":"Sam Catlow","issue_id":"archie-core-abg.21v","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Adversarial review complete. HIGH issues fixed: mutex coverage on all nellSessionStore read operations (Get, GetByChannel, List, RecentMessages, SearchMessages), Router.Store nil guard added. Remaining MEDIUM/LOW findings (truncate UTF-8, time.Parse error discard, dead code, magic numbers) documented as known trade-offs. 40/40 pass with -race."}} {"id":"int-1b928359a8f1911ad44b0013ba085335","kind":"field_change","created_at":"2026-07-26T03:56:20.690318723Z","actor":"Sam Catlow","issue_id":"archie-core-abg.19v","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Adversarial review complete. Dead code removed from finalize() (Label='' no-op). Nil guard added to loadFeatureFile(). Remaining findings (UserHomeDir error handling, single-unknown-file reporting, feature file scope) documented as known trade-offs. 40/40 pass with -race."}} +{"id":"int-d82c9cf0274bb06f4070c0846adb32cf","kind":"field_change","created_at":"2026-07-26T04:35:33.165540188Z","actor":"Sam Catlow","issue_id":"archie-core-xec","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Foundation delivered and adversarially reviewed: internal/secret package + Forge.Token migration. Provider/NATS/Telegram generalization and the three engine plugins (sops/bws/vault-openbao) tracked as separate follow-up beads (xec.1-4)."}} +{"id":"int-80a3f772feb61770c722cb3f97f1682e","kind":"field_change","created_at":"2026-07-26T04:37:50.730570728Z","actor":"Sam Catlow","issue_id":"archie-core-abg.35","extra":{"field":"status","new_value":"closed","old_value":"in_progress","reason":"Completed read-only Hermes takeover audit; findings and MVP remediation issues recorded."}} diff --git a/.beads/issues.jsonl b/.beads/issues.jsonl index 65c56fff6..a9ec3efda 100644 --- a/.beads/issues.jsonl +++ b/.beads/issues.jsonl @@ -1,3 +1,6 @@ +{"_type":"issue","id":"archie-core-abg.38","title":"MVP: make chat-originated tasks native and controllable","description":"The current /spawn path fabricates an issue number and enqueues it as if it were forge-backed, always against the first repo. The task schema has no source or identity, the workflow later performs forge labels/comments against a nonexistent issue, and /approve and /cancel are absent. Add a native chat task source routed through the same daemon-owned workflow and review gates without pretending a forge issue exists.","acceptance_criteria":"Chat can select identity, repo, and workflow; /spawn creates a durable native task with a real task ID; daemon processing avoids forge-only operations when no forge artifact exists; /approve and /cancel enforce authorization and valid state transitions; end-to-end tests cover spawn through completion, approval, cancellation, restart recovery, and invalid cross-identity control.","status":"open","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:01Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:37:01Z","dependencies":[{"issue_id":"archie-core-abg.38","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:01Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.37","title":"MVP: complete multi-identity composition and task ownership routing","description":"The multi-identity types are not instantiated by cmd/archied, and the identity loop still polls with root Config fields then drains into root Forge, Trees, Config, and repo lookup. Tasks do not persist source identity. Complete the end-to-end ownership path so overlapping repo assignments for archie and winter cannot be claimed or acted on by the wrong identity.","acceptance_criteria":"The composition root builds every configured identity with its own forge client, models/providers, repos, dispatch, and worktree manager; task records and NATS subjects carry identity; polling, claiming, processing, labels, comments, pushes, and PRs all use that identity; a production-shaped test with two identities on the same repo proves isolation.","status":"open","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-26T04:36:52Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:36:52Z","dependencies":[{"issue_id":"archie-core-abg.37","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:36:52Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.36","title":"MVP: run gateway conversations through the full agent/tool loop","description":"The Telegram responder currently calls runtime.Chat with MaxSteps=1 and no tool set. Email and webhook routers receive a nil responder. The central tool registry is empty/unconsumed; MCP transports are started without initialize/list/register/stop; the memory manager is not part of chat; skills and guardrails are not available to gateway turns. Replace the one-shot responder with one shared session-scoped conversational agent path used by Telegram, email, and webhook, preserving archie-core's daemon-owned safety boundaries.","acceptance_criteria":"A gateway turn can use approved built-in tools, configured MCP tools, memory, skills, compression, and guardrails through a multi-step agent loop; Telegram, email, and webhook share this path; tool transports are initialized, discovered, registered, and shut down; an end-to-end test proves an inbound message causes a tool call and a delivered reply.","status":"open","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T04:36:42Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:36:42Z","dependencies":[{"issue_id":"archie-core-abg.36","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:36:41Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.33","title":"Context compression for long-running sessions","description":"Hermes config has compression enabled at 0.5 threshold, protecting first 3 and last 20 messages. Sam confirmed this is a must-have for long-running sessions. Without compression, context windows fill up and sessions degrade.\n\nScope:\n- Compression threshold (fraction of context window used)\n- Target compression ratio\n- Protect first N / last N messages from compression\n- Integrate with MemoryManager (pre-compress hook already defined: OnPreCompressProvider)\n- Use the existing StreamingContextScrubber for fence-stripping during compression","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:36:25Z","started_at":"2026-07-26T00:34:36Z","closed_at":"2026-07-26T00:36:25Z","close_reason":"Context compression implemented. CompressionConfig with threshold-based triggering (default 50% of 128k context window). Protects first 3 and last 20 messages. Truncated middle replaced with statistical summary. Integrated into Telegram LLMResponder — fetches 100-message window, compresses before LLM call. 38/38 pass.","dependencies":[{"issue_id":"archie-core-abg.33","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.5.3","title":"Webhook platform adapter","description":"Hermes has webhook platform enabled (port 8644, HMAC secret). Sam confirmed webhooks are a must-have. This enables external services to push messages into archie-core's gateway for LLM processing.\n\nScope:\n- WebhookAdapter implementing gateway.Gateway interface\n- HTTP server with configurable host/port\n- Per-route HMAC validation\n- Deliver-only mode (inbound messages, no outbound send)\n- Idempotency cache for webhook deliveries\n- Prompt templates for transforming webhook payloads into messages","status":"closed","priority":0,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:39:59Z","closed_at":"2026-07-26T00:39:59Z","close_reason":"Webhook platform implemented. Gateway with HMAC validation, dot-notation template extraction, deliver-to-origin mode. 11 tests race-clean. Wired into main.go behind chat.webhook_addr config.","dependencies":[{"issue_id":"archie-core-abg.5.3","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:15Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.5.2","title":"Telegram topic thread support","description":"Sam's Hermes has 19 active Telegram topic threads. archie-core's Telegram channel treats all chats as flat DMs. Topic threads are how Sam organizes his workstreams — each thread is a separate context.\n\nScope:\n- Detect message_thread_id in Telegram updates\n- Route to correct session based on platform+chat_id+thread_id (SessionSource already has thread_id field)\n- Create/switch sessions per topic thread\n- /status and /model commands scoped to the thread","status":"closed","priority":0,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:14Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:24:04Z","started_at":"2026-07-26T00:20:00Z","closed_at":"2026-07-26T00:24:04Z","close_reason":"Delivered: ThreadID field added to gateway.Message and SessionSource. SessionStore persists thread_id. Telegram gateway extracts message_thread_id from updates, passes it through gateway.Message, and sends replies to the correct thread. threadIDString helper maps 0→'' for flat-chat backward compatibility. Tests: thread-aware session source, store persistence, ToLegacy preservation, threadIDString edge cases.","dependencies":[{"issue_id":"archie-core-abg.5.2","depends_on_id":"archie-core-abg.5","type":"parent-child","created_at":"2026-07-26T10:16:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} @@ -47,7 +50,9 @@ {"_type":"issue","id":"archie-core-abg.18","title":"[EPIC] Memory: pluggable provider architecture with file-backed persistence","description":"Pluggable memory system to match Hermes parity:\\n\\n1. **MemoryProvider interface**: Abstract interface with methods for initialize(), get_tool_schemas(), prefetch(), sync_turn(), and optional lifecycle hooks (on_session_end, on_session_switch, on_pre_compress, on_memory_write).\\n\\n2. **Built-in file-backed memory**: MEMORY.md and USER.md stored per-session/profile. LLM-callable memory tool with add/replace/remove actions. Frozen snapshot at session start (preserves prefix cache), immediate disk write on updates. Section-sign delimited entries with substring matching.\\n\\n3. **MemoryManager**: Orchestrates built-in + at most one external provider. Background serialized write executor. Prefetch with timeout (8s). Streaming context scrubber that strips injected memory spans from model output.\\n\\nRef: docs/prds/hermes-gap-analysis.md section 4","acceptance_criteria":"An external memory provider (e.g. Honcho, Mem0) can be plugged in via config. The built-in memory tool persists across sessions. Conversation context is recalled on session resume.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:22Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:22Z","dependencies":[{"issue_id":"archie-core-abg.18","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:22Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.16","title":"[EPIC] Gateway: rich message model, adapter lifecycle, session management","description":"Foundational gateway infrastructure to match Hermes parity. Three interdependent pieces:\\n\\n1. **Message model**: Replace the 3-field Message struct with a rich MessageEvent (MessageType enum: text/photo/video/audio/voice/document/sticker/command, media_urls, reply_to context, metadata dict, source). This is the wire type every adapter produces.\\n\\n2. **Adapter lifecycle**: Replace the 3-method Gateway interface with a BasePlatformAdapter interface: connect()/disconnect()/send() as required methods, plus optional overrides for typing indicators, edit/delete, image/voice/video/document send, interactive UX (clarify buttons, approval dialogs). Capability flags (supports_code_blocks, splits_long_messages, supports_async_delivery).\\n\\n3. **Session management**: SessionSource struct (platform, chat_id, chat_type, user_id, thread_id, guild_id, profile), AsyncSessionStore for persistent session storage, SessionContext for system prompt injection.\\n\\nAll three blocks together enable adding new platforms as plugins without touching core gateway code.\\n\\nRef: docs/prds/hermes-gap-analysis.md sections 1-2","acceptance_criteria":"New adapters can be added by implementing a Go interface with connect/disconnect/send + optional media methods. Messages carry full metadata through the pipeline. Sessions persist across gateway restarts.","status":"open","priority":0,"issue_type":"epic","owner":"sam@catlow.tech","created_at":"2026-07-25T14:02:21Z","created_by":"Sam Catlow","updated_at":"2026-07-25T14:02:21Z","dependencies":[{"issue_id":"archie-core-abg.16","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T00:02:21Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-jfg","title":"Spawned archie-agent containers not on daemon's docker network — can't reach NATS","description":"Root cause of 'agent still failing on the server': archied's container.Pool.Acquire creates archie-agent containers via the Docker SDK with no NetworkMode set, so Docker attaches them to the default bridge network. archied and nats run on the compose-created 'archie-core_default' network instead, so the spawned container's hostname resolution for 'nats' (from NATS_URL=nats://nats:4222) fails and archie-agent can't connect. Confirmed on carina host logs: archied logs show repeating 'taskrun request failed err=\"nats: no responders available for request\"' for every task, containers created and destroyed within ~1.5s (consistent with archie-agent's NATS client failing fast). Fixed by detecting the daemon's own container's network in NewPool (selfNetwork, via ContainerInspect on os.Hostname()) and setting HostConfig.NetworkMode on spawned containers to match.","status":"closed","priority":0,"issue_type":"bug","owner":"sam@catlow.tech","created_at":"2026-07-24T03:10:26Z","created_by":"Sam Catlow","updated_at":"2026-07-25T13:04:34Z","closed_at":"2026-07-25T13:04:34Z","close_reason":"Fix already implemented and verified: selfNetwork() in internal/container/pool.go detects the daemon's own container network via ContainerInspect(os.Hostname()) and Acquire() sets HostConfig.NetworkMode to match, so spawned archie-agent containers join the same compose network as nats. Build and internal/container tests pass.","dependency_count":0,"dependent_count":0,"comment_count":0} -{"_type":"issue","id":"archie-core-xec","title":"internal/secret: secrets-engine registry with yaegi extension interface","description":"Add a secret-management package that avoids hard-coding secrets backends. Defines an Engine interface (Name, Version, Resolve(ref string) (map[string]string, error)) that custom secrets engines implement as yaegi-interpreted .go plugins, loaded the same way internal/plugin.LoadDir already loads daemon plugins (main.Engine export, resolved via yaegiutil.Resolve). Includes a built-in compiled-in 'env' engine, a Registry type, and a config.SecretRef type ({Engine, Ref string}) that directly REPLACES the existing TokenEnv/APIKeyEnv string fields across config.go (Forge, Provider, NATSConfig, TelegramConfig, etc) -- no backwards-compatibility shim, this is a clean cutover since the end user is the repo owner, not an external customer base. Ships no third-party engines yet (sops/bws/vault-openbao are follow-up beads) but proves the extension point with the env engine and a directory-loaded custom engine in tests.","design":"Mirrors internal/plugin's Plugin interface (Name/Version) + one Resolve method. Built-in env engine is native Go (trivial, no yaegi needed) registered by default. Custom/shipped engines are yaegi .go files loaded from a configurable directory via yaegiutil.Resolve[Engine](i, src, \"main.Engine\").","acceptance_criteria":"internal/secret package exists with Engine interface, Registry, LoadDir (yaegi-based, mirrors internal/plugin conventions); config.SecretRef replaces TokenEnv/APIKeyEnv/etc fields throughout config.go and all call sites are updated; task check passes; adversarial review finds zero surviving findings.","notes":"Research done 2026-07-26: confirmed no existing internal/secret package, no beads on this topic, yaegi is the established plugin mechanism in this repo (not go-plugin/gRPC like tau). See internal/yaegiutil, internal/plugin, internal/skill/plugin.go for prior art to follow.","status":"in_progress","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:14:18Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:14:40Z","started_at":"2026-07-26T04:14:40Z","dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.39","title":"MVP: migrate Hermes profiles, memory, skills, and session state","description":"The copied live Hermes instance contains root plus agile-lead, dev, and local-agent profiles with distinct models, gateways, memories, SOUL prompts, skills, sessions, and cron state. archie-core currently has forge identities but no profile-scoped gateway/tool/memory/workspace composition and no importer. Define the mapping into archie-core identities/profiles and build a one-time idempotent migration plus cutover rehearsal.","acceptance_criteria":"Document and implement the mapping for all copied profiles; import SOUL, USER, MEMORY, relevant skills, channel/session metadata, and scheduled jobs without secrets; preserve profile isolation and session routing; produce a dry-run report; rehearse dual-run or shadow validation and a rollback-safe carina cutover checklist.","status":"open","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T04:37:09Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:37:09Z","dependencies":[{"issue_id":"archie-core-abg.39","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:37:08Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-abg.35","title":"Audit Hermes-to-archie-core MVP takeover gaps","description":"Compare the copied live Hermes state in .hermes-carina with archie-core's current runtime and backlog. Determine the minimum remaining work for archie-core to replace Hermes on carina, explicitly excluding the in-flight secret engine and provider/config work.","acceptance_criteria":"Document current capability parity, concrete blockers, minimum migration sequence, and non-MVP deferrals with file and issue evidence; do not modify implementation code.","notes":"Verdict: not cutover-ready. The copied live surface is root plus three profiles; connected Telegram/email/webhook gateways; 419 persisted session records across root state; one scheduled Gitea Monitor with Telegram delivery; enabled Linear/Gitea MCP; and actual use of terminal/file/patch/web/memory/session/delegation/process tools. Critical gaps: gateway chat is a one-step runtime.Chat call with no tools; email/webhook have nil responders; tool registry/MCP/memory are not wired end-to-end; rich gateway abstractions are parallel dead code; Telegram is instantiated with an empty allowlist; chat /spawn fabricates a forge issue and /approve,/cancel are absent; multi-identity is not composed or ownership-safe; no profile/state importer; cron/delivery/auth/webhook parity remain open. Filed abg.36 full gateway agent loop, abg.37 identity routing, abg.38 native chat tasks, abg.39 migration/cutover. Existing MVP dependencies: abg.17 stdio MCP completion, abg.22 authorization subset, abg.23 delivery, abg.24 scheduler, abg.27 webhook HMAC/filter/template/dedup subset. Focused gateway/channel/memory/tools/daemon/cmd tests passed when rerun with local socket access.","status":"closed","priority":1,"issue_type":"task","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:28:15Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:37:51Z","started_at":"2026-07-26T04:28:19Z","closed_at":"2026-07-26T04:37:51Z","close_reason":"Completed read-only Hermes takeover audit; findings and MVP remediation issues recorded.","dependencies":[{"issue_id":"archie-core-abg.35","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T14:28:14Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} +{"_type":"issue","id":"archie-core-xec","title":"internal/secret: secrets-engine registry with yaegi extension interface","description":"Add a secret-management package that avoids hard-coding secrets backends. Defines an Engine interface (Name, Version, Resolve(ref string) (map[string]string, error)) that custom secrets engines implement as yaegi-interpreted .go plugins, loaded the same way internal/plugin.LoadDir already loads daemon plugins (main.Engine export, resolved via yaegiutil.Resolve). Includes a built-in compiled-in 'env' engine, a Registry type, and a config.SecretRef type ({Engine, Ref string}) that directly REPLACES the existing TokenEnv/APIKeyEnv string fields across config.go (Forge, Provider, NATSConfig, TelegramConfig, etc) -- no backwards-compatibility shim, this is a clean cutover since the end user is the repo owner, not an external customer base. Ships no third-party engines yet (sops/bws/vault-openbao are follow-up beads) but proves the extension point with the env engine and a directory-loaded custom engine in tests.","design":"Mirrors internal/plugin's Plugin interface (Name/Version) + one Resolve method. Built-in env engine is native Go (trivial, no yaegi needed) registered by default. Custom/shipped engines are yaegi .go files loaded from a configurable directory via yaegiutil.Resolve[Engine](i, src, \"main.Engine\").","acceptance_criteria":"internal/secret package exists with Engine interface, Registry, LoadDir (yaegi-based, mirrors internal/plugin conventions) -- DONE. config.Forge.Token (SecretRef) replaces Forge.TokenEnv end-to-end including per-identity validation -- DONE. Provider/NATS/Telegram migration deferred to archie-core-xec.4 (scope narrowed mid-implementation after discovering the name-forwarding architecture fork). task check passes -- DONE. Adversarial review found zero surviving findings after fix pass -- DONE.","notes":"Delivered: internal/secret package (Engine interface, Registry, yaegi LoadDir mirroring internal/plugin conventions, built-in env engine, secretextract symbol table with nil-guarded wrapper) with adversarial-review-clean test coverage (real yaegi-loaded engine tests, panic/nil-guard/sorted-load/subdir-ignored adversarial cases). config.Forge.TokenEnv replaced with config.Forge.Token secret.SecretRef end-to-end (cmd/archied/main.go resolution, finalize() defaulting, per-identity validation requiring an explicit token with no silent default). Provider.APIKeyEnv/NATSConfig.TokenEnv/TelegramConfig.TokenEnv deliberately NOT migrated -- see archie-core-xec.4 for why (they're forwarded by name to ai-sdk/runtime and subprocess workers rather than resolved centrally; migrating needs eager-resolve-then-inject redesign first). Adversarial review (fresh agent, no context) found and fixes applied for: (1) per-identity Forge.Token had no validation -- fixed, now required explicitly; (2) Engine.Resolve interface doc didn't warn about nil-wrapper empty-string-no-error edge case -- fixed. task check (fmt/go fix/vet/build/test) clean; go test ./... clean repo-wide.","status":"closed","priority":1,"issue_type":"feature","assignee":"Sam Catlow","owner":"sam@catlow.tech","created_at":"2026-07-26T04:14:18Z","created_by":"Sam Catlow","updated_at":"2026-07-26T04:35:33Z","started_at":"2026-07-26T04:14:40Z","closed_at":"2026-07-26T04:35:33Z","close_reason":"Foundation delivered and adversarially reviewed: internal/secret package + Forge.Token migration. Provider/NATS/Telegram generalization and the three engine plugins (sops/bws/vault-openbao) tracked as separate follow-up beads (xec.1-4).","dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.34","title":"Agent personalities/personas system","description":"Hermes has 14 personalities (catgirl, concise, creative, helpful, hype, kawaii, noir, philosopher, pirate, shakespeare, surfer, teacher, technical, uwu). Sam uses these. Personalities are system prompt modifiers that change the agent's communication style.\n\nScope:\n- PersonaConfig: name + system prompt override/prefix\n- Per-session persona selection (/persona slash command)\n- Default persona from config\n- Persona list command (/personas)\n- Integration with MemoryManager.BuildSystemPrompt() (persona prompt inserted before memory context)","status":"closed","priority":1,"issue_type":"feature","owner":"sam@catlow.tech","created_at":"2026-07-26T00:16:17Z","created_by":"Sam Catlow","updated_at":"2026-07-26T00:40:00Z","closed_at":"2026-07-26T00:40:00Z","close_reason":"Persona registry implemented. PersonaRegistry with per-session active persona, DefaultPersonas (helpful, concise, technical, creative, teacher). Persona prompt injected into system prompt before memory context. 5 tests.","dependencies":[{"issue_id":"archie-core-abg.34","depends_on_id":"archie-core-abg","type":"parent-child","created_at":"2026-07-26T10:16:16Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-abg.13.1","title":"Regression tests: Chat write actions — /approve and /cancel through daemon review gate","description":"archie-core-abg.13 closed with /spawn implemented but /approve and /cancel deferred. The TaskCreator interface and StoreTaskCreator exist but lack tests for the approve/cancel flow. Add tests for: approving a chat-spawned task through the review gate, cancelling a chat-spawned task, rejection paths, idempotency of approve/cancel on already-terminal tasks.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:23Z","closed_at":"2026-07-25T23:59:23Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependencies":[{"issue_id":"archie-core-abg.13.1","depends_on_id":"archie-core-abg.13","type":"parent-child","created_at":"2026-07-26T09:39:54Z","created_by":"Sam Catlow","metadata":"{}"}],"dependency_count":0,"dependent_count":0,"comment_count":0} {"_type":"issue","id":"archie-core-iol","title":"Regression tests: NATS RPC — request timeout, reply routing, error propagation","description":"internal/natsrpc/natsrpc.go has only 1 test (envelope round trip). Missing: request timeout handling, reply-to routing correctness, error propagation through the envelope, concurrent request isolation, reconnection behavior.","status":"closed","priority":1,"issue_type":"task","owner":"sam@catlow.tech","created_at":"2026-07-25T23:39:54Z","created_by":"Sam Catlow","updated_at":"2026-07-25T23:59:23Z","closed_at":"2026-07-25T23:59:23Z","close_reason":"Regression tests added for all 8 gap areas: Telegram (split/chat/metadata/middleware), gate (Blocking/Finding/GateContext), NATS RPC (envelope/register/timeout), taskrun approve/cancel (idempotency), yaegi extract smoke tests (3 packages), events bus (ordering/slow-consumer/close), nell adapter (empty/concurrent/cancellation/oversized), container pool (error paths). All tests pass with -race.","dependency_count":0,"dependent_count":0,"comment_count":0} diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 626c07f54..42a87522d 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -142,7 +142,7 @@ Token auth via a generated `GIT_ASKPASS` helper script -- the token never appe Daemon-level TOML (`~/.config/archie/config.toml`): -- `[forge]` -- type (github), host, token env var +- `[forge]` -- type (github), host, token secret reference - `[dispatch]` -- trigger (assignee/label/either), labels, ack reaction - `[[repos]]` -- owner, name, base branch, gate commands, protected paths, ecosystem - `[models]` -- planner, builder, triage (provider/model refs) @@ -152,6 +152,8 @@ Daemon-level TOML (`~/.config/archie/config.toml`): - `[web]` -- dashboard listen address - `[notify]` -- webhook URL for notifications +Secrets (forge token, provider API keys, channel tokens) are not embedded in config files. `internal/secret` defines a pluggable `Engine` interface (`Name`, `Version`, `Resolve(key) (string, error)`) resolved through a `Registry`; the built-in `env` engine reads an environment variable by name. Custom engines (sops, Bitwarden Secrets Manager, Vault/OpenBao) are Yaegi-interpreted `.go` plugins loaded from a directory, following the same convention as `internal/plugin`'s daemon plugins. Config fields reference a secret as `{engine, key}` (`secret.SecretRef`), e.g. `token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" }`. As of this writing only `Forge.Token` has been migrated to `SecretRef`; `Provider.APIKeyEnv`, `NATSConfig.TokenEnv`, and `TelegramConfig.TokenEnv` are still plain env-var-name strings pending a follow-up (they're forwarded by name to `ai-sdk/runtime` and subprocess workers rather than resolved centrally, which needs its own design pass before migrating). + Subprocess mode is a migration transport boundary, not a security sandbox: the worker still runs under the daemon UID and can access daemon-readable host resources. The "daemon never runs untrusted code" boundary requires the later container runner with a separate user, a restricted filesystem and process namespace, and explicit mounts. Per-repo gates are command lists: `[[repos.gate]] = ["go", "vet", "./..."]`. The last command is the test runner (by convention -- TDD inverts it). diff --git a/cmd/archied/main.go b/cmd/archied/main.go index 065d72d8a..dcccd9f93 100644 --- a/cmd/archied/main.go +++ b/cmd/archied/main.go @@ -9,10 +9,10 @@ import ( "flag" "fmt" "log/slog" + "net" "os" "os/signal" "path/filepath" - "net" "strconv" "syscall" @@ -42,6 +42,7 @@ import ( "github.com/samcharles93/archie-core/internal/plugin" "github.com/samcharles93/archie-core/internal/plugin/pluginextract" + "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/storerpc" @@ -72,9 +73,10 @@ func run() int { return 1 } - token := os.Getenv(cfg.Forge.TokenEnv) - if token == "" { - fmt.Fprintln(os.Stderr, cfg.Forge.TokenEnv+" is required") + secrets := secret.NewRegistry() + token, err := cfg.Forge.Token.Resolve(secrets) + if err != nil || token == "" { + fmt.Fprintf(os.Stderr, "forge token (engine %q, key %q) is required: %v\n", cfg.Forge.Token.Engine, cfg.Forge.Token.Key, err) return 1 } forgeClient, err := forge.New(cfg.Forge.Type, token, cfg.Forge.Host, log) diff --git a/config.example.toml b/config.example.toml index 45a627e2b..f0787c13f 100644 --- a/config.example.toml +++ b/config.example.toml @@ -1,5 +1,9 @@ # archied configuration. Copy to ~/.config/archie/config.toml. -# Forge tokens are NOT configured here: export the variable named by token_env. +# Secrets are NOT configured here directly: each one is a {engine, key} +# reference resolved through a secrets engine at startup. The built-in +# "env" engine reads key as an environment variable name. Custom engines +# (sops, bws, vault/openbao, ...) are Yaegi plugins loaded from a +# directory -- see internal/secret. # work_dir = "~/.local/share/archie/work" # default # db_path = "~/.local/share/archie/archie.db" @@ -12,7 +16,7 @@ diff_cap_lines = 400 [forge] type = "github" host = "https://github.com" -token_env = "ARCHIE_GITHUB_TOKEN" +token = { engine = "env", key = "ARCHIE_GITHUB_TOKEN" } [dispatch] trigger = "assignee" # "assignee", "label", or "either" diff --git a/internal/config/config.go b/internal/config/config.go index d8bf4f486..1322c35f4 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -17,6 +17,7 @@ import ( "github.com/BurntSushi/toml" + "github.com/samcharles93/archie-core/internal/secret" ) // Duration is a time.Duration that unmarshals from TOML strings ("60s"). @@ -184,9 +185,9 @@ type Agent struct { // Forge configures the code forge integration. type Forge struct { - Type string `toml:"type" yaml:"type"` - Host string `toml:"host" yaml:"host"` - TokenEnv string `toml:"token_env" yaml:"token_env"` + Type string `toml:"type" yaml:"type"` + Host string `toml:"host" yaml:"host"` + Token secret.SecretRef `toml:"token" yaml:"token"` } // Dispatch configures how archied discovers work and reflects task state @@ -543,8 +544,8 @@ func finalize(cfg Config) (Config, error) { if cfg.Forge.Host == "" { cfg.Forge.Host = "https://github.com" } - if cfg.Forge.TokenEnv == "" { - cfg.Forge.TokenEnv = "ARCHIE_GITHUB_TOKEN" + if cfg.Forge.Token.Engine == "" && cfg.Forge.Token.Key == "" { + cfg.Forge.Token = secret.SecretRef{Engine: "env", Key: "ARCHIE_GITHUB_TOKEN"} } if cfg.Agent.Mode == "" { if cfg.Containers.Enabled { @@ -624,6 +625,9 @@ func finalize(cfg Config) (Config, error) { default: return cfg, fmt.Errorf("config: identities[%d].forge.type %q is not supported (want github or gitea)", i, id.Forge.Type) } + if id.Forge.Token == (secret.SecretRef{}) { + return cfg, fmt.Errorf("config: identities[%d].forge.token is required (each identity needs its own secret reference; unlike the top-level [forge], there is no default)", i) + } for j, r := range id.Repos { if r.Owner == "" || r.Name == "" { return cfg, fmt.Errorf("config: identities[%d].repos[%d] needs owner and name", i, j) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 4ecc145fd..c5cd5486c 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -8,6 +8,8 @@ import ( "strings" "testing" "time" + + "github.com/samcharles93/archie-core/internal/secret" ) func TestTaskConfigToConfigRoundTrip(t *testing.T) { @@ -17,7 +19,7 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) { Budgets: Budgets{MaxSteps: 12, MaxTokens: 34_000, WallClock: Duration(45 * time.Minute), GateMaxFailures: 3}, Dispatch: Dispatch{Trigger: "label", AckReaction: "eyes", Labels: map[string]string{"working": "bot:working"}}, Notify: Notify{Webhook: "https://notify.example.test/hook"}, - Forge: Forge{Type: "github", Host: "https://forge.example.test", TokenEnv: "TOP_SECRET"}, + Forge: Forge{Type: "github", Host: "https://forge.example.test", Token: secret.SecretRef{Engine: "env", Key: "TOP_SECRET"}}, } got := cfg.ForTask().ToConfig() @@ -39,8 +41,8 @@ func TestTaskConfigToConfigRoundTrip(t *testing.T) { if got.Forge.Host != cfg.Forge.Host { t.Fatalf("Forge.Host = %q, want %q", got.Forge.Host, cfg.Forge.Host) } - if got.Forge.TokenEnv != "" { - t.Fatalf("Forge.TokenEnv = %q, want empty (never carried by TaskConfig)", got.Forge.TokenEnv) + if got.Forge.Token != (secret.SecretRef{}) { + t.Fatalf("Forge.Token = %#v, want zero value (never carried by TaskConfig)", got.Forge.Token) } } @@ -64,9 +66,9 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) { }, Notify: Notify{Webhook: "https://notify.example.test/hook"}, Forge: Forge{ - Type: "github", - Host: "https://forge.example.test", - TokenEnv: "TOP_SECRET_FORGE_TOKEN", + Type: "github", + Host: "https://forge.example.test", + Token: secret.SecretRef{Engine: "env", Key: "TOP_SECRET_FORGE_TOKEN"}, }, Providers: map[string]Provider{ "secret": {APIKeyEnv: "TOP_SECRET_PROVIDER_TOKEN"}, @@ -129,13 +131,13 @@ func TestConfigForTaskJSONRoundTrip(t *testing.T) { }) { t.Fatalf("forge payload = %s, want only host", payload["forge"]) } - for _, secret := range []string{ - cfg.Forge.TokenEnv, + for _, ref := range []string{ + cfg.Forge.Token.Key, cfg.Providers["secret"].APIKeyEnv, cfg.NATS.TokenEnv, } { - if strings.Contains(string(data), secret) { - t.Fatalf("task config JSON contains credential reference %q: %s", secret, data) + if strings.Contains(string(data), ref) { + t.Fatalf("task config JSON contains credential reference %q: %s", ref, data) } } @@ -616,7 +618,7 @@ bot_user = "default-legacy" [[identities]] name = "archie" bot_user = "archie" -forge = { type = "gitea", host = "https://git.example.test", token_env = "ARCHIE_TOKEN" } +forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "ARCHIE_TOKEN" } } [[identities.repos]] owner = "sam" @@ -627,7 +629,7 @@ ecosystem = "go" [[identities]] name = "winter" bot_user = "winter" -forge = { type = "gitea", host = "https://git.example.test", token_env = "WINTER_TOKEN" } +forge = { type = "gitea", host = "https://git.example.test", token = { engine = "env", key = "WINTER_TOKEN" } } [[identities.repos]] owner = "sam" @@ -647,8 +649,8 @@ ecosystem = "go" if cfg.Identities[0].BotUser != "archie" { t.Errorf("Identities[0].BotUser = %q", cfg.Identities[0].BotUser) } - if cfg.Identities[0].Forge.TokenEnv != "ARCHIE_TOKEN" { - t.Errorf("Identities[0].Forge.TokenEnv = %q", cfg.Identities[0].Forge.TokenEnv) + if cfg.Identities[0].Forge.Token != (secret.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}) { + t.Errorf("Identities[0].Forge.Token = %#v", cfg.Identities[0].Forge.Token) } if len(cfg.Identities[0].Repos) != 1 || cfg.Identities[0].Repos[0].Name != "archie-core" { t.Errorf("Identities[0].Repos = %+v", cfg.Identities[0].Repos) @@ -659,8 +661,8 @@ ecosystem = "go" if cfg.Identities[1].BotUser != "winter" { t.Errorf("Identities[1].BotUser = %q", cfg.Identities[1].BotUser) } - if cfg.Identities[1].Forge.TokenEnv != "WINTER_TOKEN" { - t.Errorf("Identities[1].Forge.TokenEnv = %q", cfg.Identities[1].Forge.TokenEnv) + if cfg.Identities[1].Forge.Token != (secret.SecretRef{Engine: "env", Key: "WINTER_TOKEN"}) { + t.Errorf("Identities[1].Forge.Token = %#v", cfg.Identities[1].Forge.Token) } if len(cfg.Identities[1].Repos) != 1 || cfg.Identities[1].Repos[0].Name != "tau" { t.Errorf("Identities[1].Repos = %+v", cfg.Identities[1].Repos) @@ -698,6 +700,29 @@ forge = { type = "github", token_env = "X" } } } +func TestIdentitiesConfigRejectsMissingForgeToken(t *testing.T) { + // Unlike the top-level [forge], a per-identity forge has no default + // token -- each identity needs its own secret reference (e.g. + // distinct bot accounts each with their own token). Omitting it must + // be a startup error, not a silent empty-string token. + _, err := LoadBytes([]byte(` +[[identities]] +name = "archie" +bot_user = "archie" +forge = { type = "github" } + +[[identities.repos]] +owner = "sam" +name = "archie-core" +`)) + if err == nil { + t.Fatal("expected error for identity with no forge.token") + } + if !strings.Contains(err.Error(), "forge.token") { + t.Errorf("error = %q, want mention of forge.token", err.Error()) + } +} + func TestLoadBytesDoesNotExist(t *testing.T) { _, err := LoadBytes(nil) if err == nil { diff --git a/internal/config/feature_config_test.go b/internal/config/feature_config_test.go index fc47b2e8b..229907107 100644 --- a/internal/config/feature_config_test.go +++ b/internal/config/feature_config_test.go @@ -25,6 +25,8 @@ import ( "strings" "testing" "time" + + "github.com/samcharles93/archie-core/internal/secret" ) // helpers @@ -32,7 +34,7 @@ import ( // writeFile creates a file under dir with the given content. func writeFile(t *testing.T, dir, name, content string) { t.Helper() - if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0644); err != nil { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { t.Fatalf("write %s: %v", name, err) } } @@ -42,7 +44,7 @@ func tmpConfigDir(t *testing.T) string { t.Helper() d := t.TempDir() // Also create conf.d/ subdirectory for additional feature files. - if err := os.MkdirAll(filepath.Join(d, "conf.d"), 0755); err != nil { + if err := os.MkdirAll(filepath.Join(d, "conf.d"), 0o755); err != nil { t.Fatal(err) } return d @@ -275,7 +277,9 @@ identities: forge: type: gitea host: https://git.example.test - token_env: ARCHIE_TOKEN + token: + engine: env + key: ARCHIE_TOKEN repos: - owner: sam name: archie-core @@ -285,7 +289,9 @@ identities: forge: type: gitea host: https://git.example.test - token_env: WINTER_TOKEN + token: + engine: env + key: WINTER_TOKEN repos: - owner: sam name: tau @@ -305,8 +311,8 @@ identities: if cfg.Identities[1].Name != "secondary" { t.Errorf("identities[1].name = %q", cfg.Identities[1].Name) } - if cfg.Identities[0].Forge.TokenEnv != "ARCHIE_TOKEN" { - t.Errorf("identities[0].forge.token_env = %q", cfg.Identities[0].Forge.TokenEnv) + if cfg.Identities[0].Forge.Token != (secret.SecretRef{Engine: "env", Key: "ARCHIE_TOKEN"}) { + t.Errorf("identities[0].forge.token = %#v", cfg.Identities[0].Forge.Token) } } @@ -718,8 +724,8 @@ models: } // ForTask must NOT carry secret references. roundTripped := taskCfg.ToConfig() - if roundTripped.Forge.TokenEnv != "" { - t.Error("ForTask must not leak TokenEnv") + if roundTripped.Forge.Token != (secret.SecretRef{}) { + t.Error("ForTask must not leak Forge.Token") } } @@ -733,7 +739,7 @@ poll_interval = "120s" [forge] type = "github" -token_env = "GH_TOKEN" +token = { engine = "env", key = "GH_TOKEN" } [[repos]] owner = "sam" @@ -757,7 +763,7 @@ bot_user = "base" max_retries = 2 [forge] type = "github" -token_env = "BASE_TOKEN" +token = { engine = "env", key = "BASE_TOKEN" } [[repos]] owner = "sam" name = "base-repo" @@ -781,7 +787,7 @@ max_retries = 5 t.Errorf("MaxRetries = %d, want 5 (overridden by overlay)", cfg.MaxRetries) } // Inherited from base. - if cfg.Forge.TokenEnv != "BASE_TOKEN" { - t.Errorf("Forge.TokenEnv = %q, want BASE_TOKEN (inherited)", cfg.Forge.TokenEnv) + if cfg.Forge.Token != (secret.SecretRef{Engine: "env", Key: "BASE_TOKEN"}) { + t.Errorf("Forge.Token = %#v, want {env BASE_TOKEN} (inherited)", cfg.Forge.Token) } } diff --git a/internal/daemon/daemon_test.go b/internal/daemon/daemon_test.go index c845ce0fd..91d5f3385 100644 --- a/internal/daemon/daemon_test.go +++ b/internal/daemon/daemon_test.go @@ -18,6 +18,7 @@ import ( "github.com/samcharles93/archie-core/internal/config" "github.com/samcharles93/archie-core/internal/forge" arnats "github.com/samcharles93/archie-core/internal/nats" + "github.com/samcharles93/archie-core/internal/secret" "github.com/samcharles93/archie-core/internal/storage" "github.com/samcharles93/archie-core/internal/store" "github.com/samcharles93/archie-core/internal/taskrun" @@ -622,7 +623,7 @@ func TestNewIdentityRunnerPopulatesFromConfig(t *testing.T) { idCfg: config.IdentityConfig{ Name: "my-bot", BotUser: "my-bot", - Forge: config.Forge{Type: "gitea", TokenEnv: "X"}, + Forge: config.Forge{Type: "gitea", Token: secret.SecretRef{Engine: "env", Key: "X"}}, Repos: []config.Repo{{Owner: "o", Name: "r"}}, }, }, @@ -631,7 +632,7 @@ func TestNewIdentityRunnerPopulatesFromConfig(t *testing.T) { idCfg: config.IdentityConfig{ Name: "other-bot", BotUser: "other-bot", - Forge: config.Forge{Type: "github", TokenEnv: "Y"}, + Forge: config.Forge{Type: "github", Token: secret.SecretRef{Engine: "env", Key: "Y"}}, Repos: []config.Repo{{Owner: "a", Name: "b"}, {Owner: "c", Name: "d"}}, }, }, diff --git a/internal/secret/engine.go b/internal/secret/engine.go index 16e6c7553..62c9a1b00 100644 --- a/internal/secret/engine.go +++ b/internal/secret/engine.go @@ -2,15 +2,25 @@ // resolve SecretRef values (engine + key) into strings at daemon startup, // keeping credentials out of config files and environment variables. // -// Built-in engines (env, bws, sops) are compiled in; custom engines are -// loaded from a directory via Yaegi, mirroring internal/plugin conventions. +// Only the "env" engine is compiled in (see env.go). Other backends +// (sops, Bitwarden Secrets Manager, Vault/OpenBao) ship as Yaegi-loaded +// .go plugins under a configurable directory via Registry.LoadDir, +// mirroring internal/plugin conventions -- they are not hard-coded +// into the binary. package secret import ( "fmt" + "log/slog" "os" + "path/filepath" + "reflect" + "sort" + "strings" "sync" + "github.com/traefik/yaegi/interp" + "github.com/samcharles93/archie-core/internal/yaegiutil" ) @@ -23,6 +33,12 @@ type Engine interface { Version() string // Resolve looks up a secret by key and returns its value. Returns an // error when the key is unknown or the backend is unreachable. + // + // Caution for callers: a Yaegi-loaded engine whose exported value + // omits the Resolve function resolves every key to ("", nil) rather + // than failing (see secretextract's generated wrapper nil-guards) -- + // check for an empty string in addition to a non-nil error before + // trusting a resolved secret. Resolve(key string) (string, error) } @@ -60,31 +76,51 @@ func (r *Registry) Resolve(ref SecretRef) (string, error) { return e.Resolve(ref.Key) } -// LoadDir loads yaegi-interpreted secret engine plugins from a directory -// of .go files. Each file must export a "main.Engine" variable satisfying -// the Engine interface. Failed plugins are skipped; successful ones are -// registered. Returns the count of loaded engines. -func (r *Registry) LoadDir(dir string) (int, error) { +// LoadDir discovers and evaluates .go files in dir. Each file must export +// a variable named "Engine" that implements the Engine interface. Failed +// engines are logged and skipped -- the daemon starts with the remaining +// set, matching internal/plugin.LoadDir's degrade-gracefully behavior. +// Returns the count of newly registered engines. +// +// extraSymbols are additional Yaegi symbol tables made available to +// interpreted code. Callers should pass secretextract.Symbols so that +// interpreted types can satisfy the secret.Engine interface across the +// Yaegi/Go boundary. +func (r *Registry) LoadDir(dir string, extraSymbols ...map[string]map[string]reflect.Value) (int, error) { entries, err := os.ReadDir(dir) + if os.IsNotExist(err) { + return 0, nil + } if err != nil { - if os.IsNotExist(err) { - return 0, nil - } return 0, fmt.Errorf("secret: read dir %s: %w", dir, err) } - loaded := 0 - for _, entry := range entries { - if entry.IsDir() || !isGoFile(entry.Name()) { - continue + var names []string + for _, e := range entries { + if !e.IsDir() && strings.HasSuffix(e.Name(), ".go") { + names = append(names, e.Name()) } - path := dir + "/" + entry.Name() + } + sort.Strings(names) + + loaded := 0 + for _, name := range names { + path := filepath.Join(dir, name) src, err := os.ReadFile(path) if err != nil { + slog.Default().Warn("skipping unreadable secret engine", "file", name, "err", err) continue } - e, err := yaegiutil.Resolve[Engine](nil, string(src), "main.Engine") + // Each file is package main -- must use a fresh interpreter to + // avoid symbol collisions between files. + i, err := yaegiutil.New(interp.Options{}, extraSymbols...) if err != nil { + slog.Default().Warn("skipping secret engine -- interpreter setup failed", "file", name, "err", err) + continue + } + e, err := yaegiutil.Resolve[Engine](i, string(src), "main.Engine") + if err != nil { + slog.Default().Warn("skipping secret engine", "file", name, "err", err) continue } r.Register(e) @@ -108,7 +144,3 @@ func NewRegistry() *Registry { r.Register(&envEngine{}) return r } - -func isGoFile(name string) bool { - return len(name) > 3 && name[len(name)-3:] == ".go" -} diff --git a/internal/secret/loaddir_test.go b/internal/secret/loaddir_test.go new file mode 100644 index 000000000..ad653bb57 --- /dev/null +++ b/internal/secret/loaddir_test.go @@ -0,0 +1,358 @@ +package secret_test + +import ( + "os" + "path/filepath" + "testing" + + "github.com/samcharles93/archie-core/internal/secret" + "github.com/samcharles93/archie-core/internal/secret/secretextract" +) + +// ── LoadDir behavioral tests ───────────────────────────────────────── + +var symbols = secretextract.Symbols + +func TestLoadDirLoadsValidEngine(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "hello.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: func() string { return "hello" }, + WVersion: func() string { return "1.0.0" }, + WResolve: func(key string) (string, error) { return "resolved:" + key, nil }, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("LoadDir returned %d, want 1", n) + } + e, ok := r.Get("hello") + if !ok { + t.Fatal("engine \"hello\" not registered") + } + if e.Version() != "1.0.0" { + t.Errorf("Version() = %q, want 1.0.0", e.Version()) + } + v, err := e.Resolve("k") + if err != nil { + t.Fatal(err) + } + if v != "resolved:k" { + t.Errorf("Resolve() = %q, want resolved:k", v) + } +} + +func TestLoadDirSkipsInvalidEngine(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "broken.go"), []byte(`package main +this is not valid Go syntax @@@@ +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("LoadDir returned %d from broken source, want 0", n) + } +} + +func TestLoadDirSkipsFileWithoutEngineExport(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "notanengine.go"), []byte(`package main + +func Something() string { return "nope" } +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("LoadDir returned %d from file without Engine export, want 0", n) + } +} + +func TestLoadDirSkipsNonGoFiles(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "readme.md"), []byte(`# Not an engine`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "hello.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: func() string { return "hello" }, + WVersion: func() string { return "1.0.0" }, + WResolve: func(key string) (string, error) { return "v", nil }, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("LoadDir returned %d, want 1 (only .go files count)", n) + } +} + +func TestLoadDirSubdirectoriesAreIgnored(t *testing.T) { + dir := t.TempDir() + subDir := filepath.Join(dir, "nested") + if err := os.MkdirAll(subDir, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(subDir, "nested.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: func() string { return "nested" }, + WVersion: func() string { return "1.0.0" }, + WResolve: func(key string) (string, error) { return "v", nil }, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("LoadDir returned %d, want 0 -- subdirectories must not be traversed", n) + } +} + +// ── Adversarial tests ──────────────────────────────────────────────── + +func TestLoadDirNilFunctionFieldsLoadsWithoutPanic(t *testing.T) { + // A _Engine with nil WName/WVersion/WResolve must LOAD without + // panicking AND must not panic when called -- the wrapper must + // nil-guard. Otherwise resolving a secret from a malformed custom + // engine crashes the daemon. + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "nilfuncs.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: nil, + WVersion: nil, + WResolve: nil, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("LoadDir returned %d, want 1 (nil funcs should not prevent loading)", n) + } + + e, _ := r.Get("") + if name := e.Name(); name != "" { + t.Errorf("Name() = %q, want empty from nil WName", name) + } + if version := e.Version(); version != "" { + t.Errorf("Version() = %q, want empty from nil WVersion", version) + } + if v, err := e.Resolve("k"); err != nil || v != "" { + t.Errorf("Resolve() = (%q, %v), want (\"\", nil) from nil WResolve", v, err) + } +} + +func TestLoadDirSkipsEngineWithWrongExportType(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "wrongtype.go"), []byte(`package main + +var Engine = 42 +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("LoadDir returned %d from wrong-type export, want 0", n) + } +} + +func TestLoadDirSkipsEngineWithOnlySomeInterfaceMethods(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "partial.go"), []byte(`package main + +type partial struct{} +func (p partial) Name() string { return "partial" } +func (p partial) Version() string { return "1.0.0" } +// No Resolve() method -- deliberately incomplete. + +var Engine partial +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 0 { + t.Errorf("LoadDir returned %d from partial impl, want 0", n) + } +} + +func TestLoadDirEngineWithPanicInResolve(t *testing.T) { + // An engine whose Resolve() panics must still be loadable -- the + // panic only fires on call, not on load. Registry.Resolve does not + // itself recover; callers that invoke a loaded engine's Resolve are + // expected to use yaegiutil.Safe if they need panic recovery, same + // as internal/plugin callers. + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "panicky.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: func() string { return "panicky" }, + WVersion: func() string { return "1.0.0" }, + WResolve: func(key string) (string, error) { panic("boom") }, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("LoadDir returned %d, want 1 (panics are deferred to call time)", n) + } + + e, _ := r.Get("panicky") + func() { + defer func() { + if rec := recover(); rec == nil { + t.Error("Resolve() did not panic -- expected panic from panicky engine") + } + }() + _, _ = e.Resolve("k") + }() +} + +func TestLoadDirMultipleEnginesSortedByFilename(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "01-alpha.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: func() string { return "alpha" }, + WVersion: func() string { return "1.0.0" }, + WResolve: func(key string) (string, error) { return "v", nil }, +} +`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(dir, "02-beta.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: func() string { return "beta" }, + WVersion: func() string { return "2.0.0" }, + WResolve: func(key string) (string, error) { return "v", nil }, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 2 { + t.Fatalf("LoadDir returned %d, want 2", n) + } + if _, ok := r.Get("alpha"); !ok { + t.Error("alpha engine not registered") + } + if _, ok := r.Get("beta"); !ok { + t.Error("beta engine not registered") + } +} + +func TestGeneratedWrapperHasNilGuards(t *testing.T) { + // If go generate is re-run on secretextract, it overwrites the + // generated wrapper with Yaegi's default (no nil-guards). This test + // fails loudly if that happens -- a custom engine that omits + // WResolve would otherwise panic the daemon on first secret lookup. + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "nilguard.go"), []byte(`package main + +import "github.com/samcharles93/archie-core/internal/secret" + +var Engine = secret._Engine{ + WName: nil, + WVersion: nil, + WResolve: nil, +} +`), 0o644); err != nil { + t.Fatal(err) + } + + r := secret.NewRegistry() + n, err := r.LoadDir(dir, symbols) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatal("engine with nil funcs not loaded") + } + + e, _ := r.Get("") + func() { + defer func() { + if rec := recover(); rec != nil { + t.Fatalf("Name()/Version()/Resolve() panicked with nil funcs -- "+ + "the generated _Engine wrapper is missing nil guards. "+ + "Re-run of `go generate` may have overwritten them: %v", rec) + } + }() + _ = e.Name() + _ = e.Version() + _, _ = e.Resolve("k") + }() +} diff --git a/internal/secret/secret.go b/internal/secret/secret.go index c00f5a801..386440d87 100644 --- a/internal/secret/secret.go +++ b/internal/secret/secret.go @@ -1,10 +1,5 @@ package secret -import ( - "fmt" - "os" -) - // SecretRef references a secret stored in a named engine. It replaces // the previous TokenEnv/APIKeyEnv string fields throughout config. // @@ -16,36 +11,20 @@ import ( // [providers.deepseek] // api_key = {engine = "bws", key = "DEEPSEEK_API_KEY"} // -// The zero value (empty engine, empty key) resolves to "" with no error -// for backward compatibility with optional secrets. +// The zero value (empty engine, empty key) resolves to "" with no error, +// for config fields where the secret is optional (e.g. an unconfigured +// channel token). type SecretRef struct { Engine string `toml:"engine" yaml:"engine" json:"engine"` Key string `toml:"key" yaml:"key" json:"key"` } -// Resolve resolves this reference through the default registry. Returns -// "" when the reference is empty (engine and key both empty — the -// zero-value means "not configured"). +// Resolve resolves this reference through reg. Returns "" with no error +// when the reference is empty (engine and key both empty — the zero +// value means "not configured"). func (s SecretRef) Resolve(reg *Registry) (string, error) { if s.Engine == "" && s.Key == "" { return "", nil } return reg.Resolve(s) } - -// ResolveOrEnv resolves through the registry, falling back to the -// environment when no engine is configured but a key is set. This -// provides backward compatibility during migration. -func (s SecretRef) ResolveOrEnv(reg *Registry) (string, error) { - if s.Engine == "" && s.Key == "" { - return "", nil - } - if s.Engine == "" { - // Fallback: treat Key as an env var name. - if v, ok := os.LookupEnv(s.Key); ok { - return v, nil - } - return "", fmt.Errorf("secret env var %q is not set", s.Key) - } - return reg.Resolve(s) -} diff --git a/internal/secret/secret_test.go b/internal/secret/secret_test.go index e5959fae5..60518e9db 100644 --- a/internal/secret/secret_test.go +++ b/internal/secret/secret_test.go @@ -45,30 +45,6 @@ func TestSecretRefZeroValue(t *testing.T) { } } -func TestSecretRefResolveOrEnvFallback(t *testing.T) { - os.Setenv("FALLBACK_TEST_KEY", "fallback-val") - defer os.Unsetenv("FALLBACK_TEST_KEY") - - r := NewRegistry() - s := SecretRef{Key: "FALLBACK_TEST_KEY"} // no engine → env fallback - v, err := s.ResolveOrEnv(r) - if err != nil { - t.Fatal(err) - } - if v != "fallback-val" { - t.Errorf("got %q, want fallback-val", v) - } -} - -func TestSecretRefResolveOrEnvMissing(t *testing.T) { - r := NewRegistry() - s := SecretRef{Key: "NONEXISTENT_VAR_12345"} - _, err := s.ResolveOrEnv(r) - if err == nil { - t.Error("expected error for missing env var in fallback") - } -} - func TestRegistryRegisterAndGet(t *testing.T) { r := NewRegistry() e, ok := r.Get("env") diff --git a/internal/secret/secretextract/github_com-samcharles93-archie-core-internal-secret.go b/internal/secret/secretextract/github_com-samcharles93-archie-core-internal-secret.go new file mode 100644 index 000000000..ebcb7c10e --- /dev/null +++ b/internal/secret/secretextract/github_com-samcharles93-archie-core-internal-secret.go @@ -0,0 +1,54 @@ +// Code generated by 'yaegi extract github.com/samcharles93/archie-core/internal/secret'. DO NOT EDIT. + +package secretextract + +import ( + "github.com/samcharles93/archie-core/internal/secret" + "reflect" +) + +func init() { + Symbols["github.com/samcharles93/archie-core/internal/secret/secret"] = map[string]reflect.Value{ + // function, constant and variable definitions + "DefaultRegistry": reflect.ValueOf(secret.DefaultRegistry), + "NewRegistry": reflect.ValueOf(secret.NewRegistry), + + // type definitions + "Engine": reflect.ValueOf((*secret.Engine)(nil)), + "Registry": reflect.ValueOf((*secret.Registry)(nil)), + "SecretRef": reflect.ValueOf((*secret.SecretRef)(nil)), + + // interface wrapper definitions + "_Engine": reflect.ValueOf((*_github_com_samcharles93_archie_core_internal_secret_Engine)(nil)), + } +} + +// _github_com_samcharles93_archie_core_internal_secret_Engine is an interface wrapper for Engine type +// generated by 'yaegi extract'. IValue is required by Yaegi's interface bridging -- +// it holds the underlying concrete value for the interpreter's type system even +// though Name()/Resolve()/Version() delegate to the function fields. Do not remove. +type _github_com_samcharles93_archie_core_internal_secret_Engine struct { + IValue interface{} + WName func() string + WResolve func(key string) (string, error) + WVersion func() string +} + +func (W _github_com_samcharles93_archie_core_internal_secret_Engine) Name() string { + if W.WName == nil { + return "" + } + return W.WName() +} +func (W _github_com_samcharles93_archie_core_internal_secret_Engine) Resolve(key string) (string, error) { + if W.WResolve == nil { + return "", nil + } + return W.WResolve(key) +} +func (W _github_com_samcharles93_archie_core_internal_secret_Engine) Version() string { + if W.WVersion == nil { + return "" + } + return W.WVersion() +} diff --git a/internal/secret/secretextract/secretextract.go b/internal/secret/secretextract/secretextract.go new file mode 100644 index 000000000..3908f36b8 --- /dev/null +++ b/internal/secret/secretextract/secretextract.go @@ -0,0 +1,16 @@ +// Package secretextract holds the Yaegi symbol table for internal/secret, +// generated by `go generate`. Kept separate from internal/secret itself +// so the generated file can import it without a self-import cycle. +// +// IMPORTANT: Running `go generate` overwrites the generated file with +// Yaegi's default wrapper which does NOT include nil-guards on function +// fields. The `TestGeneratedWrapperHasNilGuards` test catches this if +// regeneration strips the guards. Re-apply nil-guards manually after +// regeneration until Yaegi supports generating them natively. +package secretextract + +import "reflect" + +//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name secretextract github.com/samcharles93/archie-core/internal/secret + +var Symbols = map[string]map[string]reflect.Value{} diff --git a/internal/secret/secretextract/secretextract_test.go b/internal/secret/secretextract/secretextract_test.go new file mode 100644 index 000000000..691e54dfa --- /dev/null +++ b/internal/secret/secretextract/secretextract_test.go @@ -0,0 +1,59 @@ +package secretextract + +import ( + "reflect" + "testing" +) + +func TestSymbolsContainsExpectedEngineEntries(t *testing.T) { + pkgKey := "github.com/samcharles93/archie-core/internal/secret/secret" + pkg, ok := Symbols[pkgKey] + if !ok { + t.Fatalf("Symbols missing key %q", pkgKey) + } + + if v, ok := pkg["NewRegistry"]; !ok { + t.Error("NewRegistry missing from Symbols") + } else if v.Kind() != reflect.Func { + t.Errorf("NewRegistry kind = %v, want Func", v.Kind()) + } + + if v, ok := pkg["Registry"]; !ok { + t.Error("Registry missing from Symbols") + } else if v.Kind() != reflect.Pointer { + t.Errorf("Registry kind = %v, want Ptr", v.Kind()) + } + + if v, ok := pkg["Engine"]; !ok { + t.Error("Engine missing from Symbols") + } else if v.Kind() != reflect.Pointer { + t.Errorf("Engine kind = %v, want Ptr", v.Kind()) + } + + if v, ok := pkg["SecretRef"]; !ok { + t.Error("SecretRef missing from Symbols") + } else if v.Kind() != reflect.Pointer { + t.Errorf("SecretRef kind = %v, want Ptr", v.Kind()) + } +} + +func TestGeneratedWrapperHasNilGuards(t *testing.T) { + pkgKey := "github.com/samcharles93/archie-core/internal/secret/secret" + pkg := Symbols[pkgKey] + + engineType, ok := pkg["Engine"] + if !ok { + t.Fatal("Engine missing from Symbols") + } + + kind := engineType.Kind() + if kind != reflect.Interface && kind != reflect.Pointer { + t.Errorf("Engine type kind = %v, want Interface or Ptr", kind) + } + if kind == reflect.Interface { + methodCount := engineType.Type().NumMethod() + if methodCount < 3 { + t.Errorf("Engine interface has %d methods, expected at least 3 (Name, Version, Resolve)", methodCount) + } + } +}