Skip to content

feat(security): credentialed exec + HTTP RBAC + API key cache (#197)#199

Merged
viettranx merged 14 commits intomainfrom
feat/197-credentialed-exec
Mar 15, 2026
Merged

feat(security): credentialed exec + HTTP RBAC + API key cache (#197)#199
viettranx merged 14 commits intomainfrom
feat/197-credentialed-exec

Conversation

@mrgoonie
Copy link
Contributor

@mrgoonie mrgoonie commented Mar 14, 2026

Summary

Implements secure CLI credential injection for agents with full HTTP RBAC enforcement and API key authentication. Includes changes from PR #208 (API key management, now closed).

Credentialed Exec (Core Feature)

  • Secure CLI credential injection via secure_cli_binaries table (AES-256-GCM encrypted env vars)
  • Binary path verification, shell operator detection, deny pattern regex matching
  • Sandbox-first execution — fails if sandbox unavailable (no silent host fallback)
  • Credential scrubbing from all tool output (regex + exact value matching)
  • Built-in presets for gh, gcloud, aws, kubectl, terraform
  • Full CRUD UI for CLI credentials management (admin-only)

API Key Management

  • Multiple API keys with fine-grained RBAC scopes (operator.admin, operator.write, operator.read)
  • SHA-256 key hashing, 8-char display prefix, expiration, revocation
  • WebSocket RPC + HTTP endpoints for key CRUD (admin-only)
  • Full UI for API key creation and management

HTTP RBAC Enforcement

  • resolveAuth() / requireAuth() middleware across all 25+ HTTP handlers
  • Role hierarchy: Admin > Operator > Viewer with HTTP method auto-detection
  • Constant-time token comparison via subtle.ConstantTimeCompare
  • In-memory API key cache: 5-min TTL, negative caching (capped at 10K entries), pubsub invalidation
  • Backward compatible: no gateway token configured → operator role

Security Hardening (from code review)

  • Sandbox fallback defaults to FAIL, not silent host execution
  • Negative cache size capped to prevent DoS via token spraying
  • TouchLastUsed goroutine has 5s timeout to prevent connection leaks
  • secure_cli endpoints require Admin role (not Operator)
  • Column allowlist for execMapUpdate in secure CLI store

Other

  • Interactive API docs (Swagger UI at /docs)
  • Comprehensive API documentation (HTTP, WebSocket RPC, API keys)
  • SQL migration 000020: secure_cli_binaries + api_keys tables
  • 14 unit tests for cache and RBAC with race detector coverage

Test plan

  • go build ./... passes
  • go vet ./... passes
  • go test -race ./internal/http/... — 14/14 tests pass
  • Manual test: create API key, use it to access endpoints with correct/insufficient scope
  • Manual test: create CLI credential, verify sandbox execution
  • Manual test: verify admin-only access for credential and API key management
  • Verify migration 000020 applies cleanly on fresh DB and after main's migration 019

#197)

Direct Exec Mode prevents shell injection when credentials are injected via docker exec -e.
Includes migration, store layer, HTTP CRUD API with 5 presets (gh, gcloud, aws, kubectl, terraform),
Web UI credential management, sandbox environment support, system prompt integration, and agent awareness via TOOLS.md context.
- H1: Use [REDACTED] placeholder for credential scrub values (not [SERVER_IP])
- H2: Add field allowlist to handleUpdate to prevent column injection
- H3: Sort ListPresetNames output alphabetically
claude and others added 6 commits March 15, 2026 02:42
Implements a multi-key API key management system for the GoClaw gateway,
replacing the single-token auth model with support for multiple API keys
each with configurable permission scopes.

Backend:
- Migration 000019: api_keys table with SHA-256 hashed keys, scopes,
  expiry, and revocation support
- Store layer: APIKeyStore interface + PG implementation with indexed
  hash lookups and expiry checks
- Key generation: goclaw_ prefixed keys with SHA-256 hashing (show once)
- Auth integration: HTTP Bearer + WebSocket connect both resolve API keys
  and derive roles from scopes (admin/read/write/approvals/pairing)
- HTTP API: GET/POST/DELETE /v1/api-keys (admin-only)
- WebSocket RPC: api_keys.list, api_keys.create, api_keys.revoke
- Permissions: all API key methods require admin role

Web UI:
- API Keys management page with list, create dialog, revoke confirmation
- Show-once key display with copy-to-clipboard
- Scope checkboxes and configurable expiry (never/7d/30d/90d)
- Full i18n support (en/vi/zh)
- Sidebar navigation under System group

https://claude.ai/code/session_017sg1fT9pN25DsArUxyGxHK
Serve OpenAPI 3.0 spec at /v1/openapi.json and Swagger UI at /docs
with embedded spec covering all HTTP endpoints. Add API Docs link
to sidebar with i18n support (en/vi/zh).

https://claude.ai/code/session_017sg1fT9pN25DsArUxyGxHK
- 18-http-api.md: Complete HTTP REST API reference covering 130+ endpoints
  across 23 sections (chat, agents, skills, providers, MCP, memory, KG, etc.)
- 19-websocket-rpc.md: Full WebSocket RPC method catalog with 64+ methods,
  permission matrix, event types, and Mermaid flow diagrams
- 20-api-keys-auth.md: API key authentication model, RBAC scopes, security
  design (SHA-256 hashing, show-once), database schema, usage examples
- Updated changelog with API keys and docs entries

https://claude.ai/code/session_017sg1fT9pN25DsArUxyGxHK
- Features: add API key management to Security section, update Web Dashboard
- API section: replace old links with table linking to new docs (HTTP API,
  WebSocket RPC, API Keys & Auth, Gateway Protocol) + mention Swagger UI
- Security section: add API key management entry with doc link
- Project Status: add API keys and Swagger UI entries

https://claude.ai/code/session_017sg1fT9pN25DsArUxyGxHK
- Move expiry check from Go to SQL WHERE clause (prevent race condition)
- Extract permissions.ValidScope() to deduplicate scope validation
- Change DELETE to POST /v1/api-keys/{id}/revoke (semantic correctness)
- Handle unmarshal error in WS revoke handler
- Remove redundant allKeys field from APIKeysHandler
- Sanitize error messages (no internal err.Error() to client)
- Fix display prefix to use hex part instead of goclaw_ prefix
- Replace raw div overlay with accessible Radix Dialog
OAuth token format (sk-ant-oat01-*) should be passed as anthropic_api_key,
not claude_code_oauth_token which expects a different auth flow (OIDC).
@viettranx
Copy link
Contributor

Nâng sql lên 20 đi anh, em đang làm cái 19

Another maintainer is working on migration 19, so bump api_keys migration
to 000020 and update RequiredSchemaVersion + doc references accordingly.
@mrgoonie
Copy link
Contributor Author

Nâng sql lên 20 đi anh, em đang làm cái 19

done! 🫡

- Add ResetCredentialScrubValues() to prevent memory leak from global
  credential scrub accumulation; reset on CRUD mutations
- Add store-layer field allowlist in PGSecureCLIStore.Update() as
  defense-in-depth against column name injection
- Add secure_cli_binaries to tablesWithUpdatedAt map
- Propagate request context in buildCredentialCLIContext instead of
  context.Background()
- Log warning on sandbox-to-host fallback for credentialed exec
- Fix jsonOrEmpty for JSONB array columns (deny_args, deny_verbose)
- Add Vietnamese i18n translation for CLI Credentials sidebar
- Log invalid deny regex patterns instead of silent skip
- Add edit mode indicator for encrypted credentials in form dialog
Merge feat/208-api-key-management into feat/197-credentialed-exec.
Resolves conflicts in shared files (stores, factory, sidebar, i18n,
version, changelog, routes) keeping both feature additions.
… all HTTP handlers

- Add shared tryAuth()/tryAuthBearer() in auth.go with API key fallback
- Update all 20+ HTTP handlers to use tryAuth() instead of direct token comparison
- Fix constant-time comparison in WS connect (router.go) and tokenAuthMiddleware (server.go)
- Fix RoleFromScopes: map approvals/pairing scopes to RoleOperator
- Add name length validation (max 100) in API key create handler
- Add HasMinRole() helper to permissions package
- Wire SetPackageAPIKeyStore() in gateway startup

Note: HTTP RBAC enforcement (role-based access per endpoint) deferred to next commit.
- Add in-memory API key cache with TTL, negative caching (capped at 10K
  entries), and pubsub invalidation via bus.CacheKindAPIKeys
- Add resolveAuth/requireAuth middleware with role-based access control
  across all 25+ HTTP handlers (admin/operator/viewer)
- Enforce Admin role for secure CLI credential management endpoints
- Add constant-time token comparison via subtle.ConstantTimeCompare
- Sandbox fallback now fails instead of silently downgrading to host exec
- Add 5s timeout to TouchLastUsed fire-and-forget goroutine
- Merge SQL migrations 19+20 into single migration 000020
- Add 14 unit tests for cache and RBAC with race detector coverage
- Remove deprecated tryAuth/tryAuthBearer shims
@viettranx viettranx changed the title feat(tools): credentialed exec — secure CLI credential injection (#197) feat(security): credentialed exec + HTTP RBAC + API key cache (#197) Mar 15, 2026
@viettranx viettranx merged commit 75c570e into main Mar 15, 2026
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants