Require auth on /api/v1/ and derive capability guards server-side

Findings 1 and 2 of REVIEW-2026-07-30.md, which must land together: every
workspace capability registered with enabled=false, so the only working
provider could never execute. Fixing that alone would have turned a dead
execution path into a reachable one on an unauthenticated port.

Auth: a shared bearer token (HEXIS_API_TOKEN) is now required on the whole
/api/v1/ surface, compared with crypto/subtle.ConstantTimeCompare. /health
and /ready stay open for probes. It fails closed twice over — hexisd refuses
to start with an empty token, and the middleware returns 503 rather than ever
serving unauthenticated.

Guards: `enabled` and `requires_confirmation` are no longer readable from the
request body at all. Previously the handler derived the correct §4.3 default
and then let the caller override it, which is worse than no guard because it
reads as enforced. Both are now derived from the risk tier by shared helpers
in domain, used by the HTTP and provider registration paths alike;
unrecognised tiers fail closed to requiring confirmation.

BuildCapabilities sets Enabled, RequiresConfirmation and TimeoutSeconds
explicitly, and hexisd reconciles drifted rows on startup instead of skipping
any capability whose ID already exists — without that, allowlist edits never
reach an existing database.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Uea55zaiWuEByEDC4UBSdd
This commit is contained in:
kami
2026-07-30 23:39:13 +04:00
parent 945e4ba1ac
commit c7325a20d4
7 changed files with 368 additions and 90 deletions
+70 -47
View File
@@ -1,6 +1,7 @@
package api
import (
"crypto/subtle"
"encoding/json"
"errors"
"net/http"
@@ -11,15 +12,20 @@ import (
"github.com/kami/hexis/internal/domain"
"github.com/kami/hexis/internal/execution"
"github.com/kami/hexis/internal/storage"
"github.com/kami/hexis/internal/wire"
)
type Handler struct {
store storage.Interface
engine *execution.Engine
store storage.Interface
engine *execution.Engine
authToken string
}
func NewHandler(store storage.Interface, engine *execution.Engine) *Handler {
return &Handler{store: store, engine: engine}
// NewHandler builds the HTTP handler. authToken is the shared bearer token
// required on every /api/v1/ request; if it is empty the API refuses all
// /api/v1/ traffic rather than serving it unauthenticated.
func NewHandler(store storage.Interface, engine *execution.Engine, authToken string) *Handler {
return &Handler{store: store, engine: engine, authToken: authToken}
}
// SupportedAPIVersion is the version this server implements. A request
@@ -37,10 +43,42 @@ func (h *Handler) Register(mux *http.ServeMux) {
api.HandleFunc("/api/v1/capabilities/", h.handleCapabilityByID)
api.HandleFunc("/api/v1/execute", h.handleExecute)
api.HandleFunc("/api/v1/confirmations", h.handleConfirmations)
api.HandleFunc("/api/v1/executions", h.handleExecutions)
api.HandleFunc("/api/v1/executions/", h.handleExecutionByID)
api.HandleFunc("/api/v1/changes", h.handleChanges)
mux.Handle("/api/v1/", versionCheck(api))
mux.Handle("/api/v1/", h.requireAuth(versionCheck(api)))
}
// requireAuth enforces the shared bearer token on the whole /api/v1/ surface.
// /health and /ready stay open so probes keep working.
func (h *Handler) requireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if h.authToken == "" {
// Fail closed: an unset token must never mean "no auth required".
writeJSON(w, http.StatusServiceUnavailable, errorResponse("server misconfigured: HEXIS_API_TOKEN is not set"))
return
}
presented, ok := bearerToken(r)
if !ok || subtle.ConstantTimeCompare([]byte(presented), []byte(h.authToken)) != 1 {
w.Header().Set("WWW-Authenticate", `Bearer realm="hexis"`)
writeJSON(w, http.StatusUnauthorized, errorResponse("unauthorized"))
return
}
next.ServeHTTP(w, r)
})
}
func bearerToken(r *http.Request) (string, bool) {
h := r.Header.Get("Authorization")
if h == "" {
return "", false
}
const prefix = "bearer "
if len(h) <= len(prefix) || !strings.EqualFold(h[:len(prefix)], prefix) {
return "", false
}
return strings.TrimSpace(h[len(prefix):]), true
}
func versionCheck(next http.Handler) http.Handler {
@@ -88,45 +126,25 @@ func (h *Handler) listCapabilities(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusInternalServerError, errorResponse(err.Error()))
return
}
if caps == nil {
caps = []*domain.Capability{}
}
var apiCaps []map[string]any
for _, c := range caps {
apiCaps = append(apiCaps, map[string]any{
"capability_id": c.ID,
"id": c.ID,
"name": c.Name,
"description": c.Description,
"target_types": c.TargetTypes,
"target_entity_id": c.TargetEntityID,
"provider": c.Provider,
"operation": c.Operation,
"risk": c.Risk,
"read_only": c.ReadOnly,
"expected_side_effects": c.ExpectedSideEffects,
})
}
writeJSON(w, http.StatusOK, apiCaps)
// wire.Capabilities is the single serializer shared with the MCP adapter
// and pkg/client; it also carries the server-derived `enabled` and
// `requires_confirmation` fields this endpoint previously omitted.
writeJSON(w, http.StatusOK, wire.Capabilities(caps))
}
func (h *Handler) createCapability(w http.ResponseWriter, r *http.Request) {
var req struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
TargetTypes []string `json:"target_types"`
TargetEntityID string `json:"target_entity_id,omitempty"`
Provider string `json:"provider"`
Operation string `json:"operation"`
Risk string `json:"risk,omitempty"`
ReadOnly bool `json:"read_only"`
ExpectedSideEffects string `json:"expected_side_effects,omitempty"`
RequiresConfirmation bool `json:"requires_confirmation,omitempty"`
Enabled *bool `json:"enabled,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
Attributes map[string]any `json:"attributes,omitempty"`
Name string `json:"name"`
Description string `json:"description,omitempty"`
TargetTypes []string `json:"target_types"`
TargetEntityID string `json:"target_entity_id,omitempty"`
Provider string `json:"provider"`
Operation string `json:"operation"`
Risk string `json:"risk,omitempty"`
ReadOnly bool `json:"read_only"`
ExpectedSideEffects string `json:"expected_side_effects,omitempty"`
TimeoutSeconds int `json:"timeout_seconds,omitempty"`
Attributes map[string]any `json:"attributes,omitempty"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
writeJSON(w, http.StatusBadRequest, errorResponse("invalid JSON"))
@@ -137,11 +155,16 @@ func (h *Handler) createCapability(w http.ResponseWriter, r *http.Request) {
return
}
// Destructive capabilities are disabled by default and must be turned on
// explicitly (ECOSYSTEM-SPEC.md §4.3).
enabled := req.Risk != "destructive"
if req.Enabled != nil {
enabled = *req.Enabled
// `enabled` and `requires_confirmation` are derived server-side from the
// risk tier and are deliberately NOT settable from the request body — a
// caller-supplied override would make the ECOSYSTEM-SPEC.md §4.3 guards
// opt-out for the untrusted caller they exist to constrain.
enabled := domain.EnabledForRisk(req.Risk)
requiresConfirmation := domain.RequiresConfirmationForRisk(req.Risk)
timeoutSeconds := req.TimeoutSeconds
if timeoutSeconds <= 0 {
timeoutSeconds = domain.DefaultCapabilityTimeoutSeconds
}
now := time.Now().UTC()
@@ -156,9 +179,9 @@ func (h *Handler) createCapability(w http.ResponseWriter, r *http.Request) {
Risk: req.Risk,
ReadOnly: req.ReadOnly,
ExpectedSideEffects: req.ExpectedSideEffects,
RequiresConfirmation: req.RequiresConfirmation,
RequiresConfirmation: requiresConfirmation,
Enabled: enabled,
TimeoutSeconds: req.TimeoutSeconds,
TimeoutSeconds: timeoutSeconds,
Attributes: req.Attributes,
CreatedAt: now,
UpdatedAt: now,