Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions cmd/clawctl-hub/service_token_route_denial_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
package main

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/teddashh/AI-Intune/internal/operatoragent"
"github.com/teddashh/AI-Intune/internal/store"
)

// A valid token on a route outside its allowlist gets 403 naming the layer,
// and never spends the brute-force budget; a bad token stays a generic 401.
func TestServiceTokenRouteNotAllowlisted(t *testing.T) {
st := boundaryStore(t)
actor, err := st.CreateFirstAdmin("admin", usersPassword)
if err != nil {
t.Fatal(err)
}
allow := []string{"GET /v1/operator/machines"}
_, secret, err := st.CreateServiceToken(store.ServiceToken{Name: "reader", Scope: "view", ExpiresAt: time.Now().Add(time.Hour), Allowlist: allow}, actor.AccountID)
if err != nil {
t.Fatal(err)
}
mux := http.NewServeMux()
for _, route := range []string{"GET /v1/operator/machines", "GET /v1/operator/jobs"} {
mux.HandleFunc(route, func(w http.ResponseWriter, _ *http.Request) { w.WriteHeader(204) })
}
mux.HandleFunc("GET /v1/operator/service-tokens/self", http.NotFoundHandler().ServeHTTP)
b := newOperatorBoundary(mux, nil, st, operatorRoutePolicies, testOperatorAuthority)
b.serviceAttempts = newIPLimiter(1, 2) // two failures allowed
do := func(path, auth string) *httptest.ResponseRecorder {
req := newBoundaryRequest("GET", path, nil)
req.Header.Set("Authorization", "Bearer "+auth)
rec := httptest.NewRecorder()
b.ServeHTTP(rec, req)
return rec
}
for i := 0; i < 5; i++ {
rec := do("/v1/operator/jobs", secret)
var body struct {
Code string `json:"code"`
}
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if rec.Code != 403 || body.Code != "ROUTE_NOT_ALLOWLISTED" {
t.Fatalf("denied route: %d %s", rec.Code, rec.Body.String())
}
}
if rec := do("/v1/operator/machines", secret); rec.Code != 204 {
t.Fatalf("route denials spent the failure budget: %d", rec.Code)
}
bad := secret[:len(secret)-1] + "A"
if bad == secret {
bad = secret[:len(secret)-1] + "B"
}
if rec := do("/v1/operator/jobs", bad); rec.Code != 401 {
t.Fatalf("bad token: %d", rec.Code)
}
rec := do("/v1/operator/service-tokens/self", secret)
var self struct {
Allowlist []string `json:"allowlist"`
}
if rec.Code != 200 || json.Unmarshal(rec.Body.Bytes(), &self) != nil || len(self.Allowlist) != 1 || self.Allowlist[0] != allow[0] {
t.Fatalf("self: %d %s", rec.Code, rec.Body.String())
}
}

// Every MCP tool declares its Hub routes, and each one is a registered Hub
// route, so tools/list filtering cannot drift from the Hub. Tools whose routes
// a service token can never hold are simply never listed for a token.
func TestOperatorToolRoutesAreRegistered(t *testing.T) {
for _, tool := range operatoragent.Tools() {
routes := operatoragent.ToolRoutes(tool.Name)
if len(routes) == 0 {
t.Errorf("%s declares no routes", tool.Name)
}
for _, route := range routes {
if _, ok := operatorRoutePolicies[route]; !ok {
t.Errorf("%s: %s is not a registered Hub route", tool.Name, route)
}
}
}
}
7 changes: 6 additions & 1 deletion cmd/clawctl-hub/service_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,11 @@ func (b *operatorBoundary) serveServiceToken(w http.ResponseWriter, r *http.Requ
writeOperatorBoundaryError(response, operatorJSON, 403, "SERVICE_TOKEN_SCOPE_REQUIRED", "This action requires operator-admin scope")
return
}
if errors.Is(err, store.ErrServiceRouteNotAllowed) {
// A valid credential is not a guessing attempt: name the denying layer.
writeOperatorBoundaryError(response, operatorJSON, 403, "ROUTE_NOT_ALLOWLISTED", "This route is not in the service token's allowlist")
return
}
if err != nil || !policy.ServiceTokenEligible.eligible() || (policy.Permission == operatorauth.Admin && policy.ServiceTokenEligible != serviceEligibleOperatorAdmin) {
b.serviceAttempts.allow(source)
writeOperatorBoundaryError(response, operatorJSON, 401, "UNAUTHENTICATED", "Authentication required")
Expand All @@ -502,7 +507,7 @@ func (b *operatorBoundary) serveServiceToken(w http.ResponseWriter, r *http.Requ
response.Header().Set("Cache-Control", "no-store")
response.Header().Set("Content-Type", "application/json")
if r.Method == "GET" {
_ = json.NewEncoder(response).Encode(map[string]any{"id": token.ID, "name": token.Name, "scope": token.Scope, "expires_at": token.ExpiresAt, "max_expiry": token.MaxExpiry()})
_ = json.NewEncoder(response).Encode(map[string]any{"id": token.ID, "name": token.Name, "scope": token.Scope, "expires_at": token.ExpiresAt, "max_expiry": token.MaxExpiry(), "allowlist": token.Allowlist})
return
}
r.Body = http.MaxBytesReader(response, r.Body, 1024)
Expand Down
2 changes: 1 addition & 1 deletion cmd/clawctl-hub/service_tokens_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ func TestServiceTokenBoundary(t *testing.T) {
for _, c := range []struct {
method, path, peer, origin string
status int
}{{"GET", "/v1/operator/machines", "192.0.2.1:1234", "", 204}, {"GET", "/v1/operator/jobs", "192.0.2.1:1234", "", 401}, {"GET", "/v1/operator/machines", "198.51.100.1:1234", "", 401}, {"POST", "/v1/operator/admin", "192.0.2.1:1234", "", 401}, {"POST", "/v1/operator/test", "192.0.2.1:1234", "https://other.example.com", 403}, {"GET", "/account/service-tokens", "192.0.2.1:1234", "", 401}} {
}{{"GET", "/v1/operator/machines", "192.0.2.1:1234", "", 204}, {"GET", "/v1/operator/jobs", "192.0.2.1:1234", "", 403}, {"GET", "/v1/operator/machines", "198.51.100.1:1234", "", 401}, {"POST", "/v1/operator/admin", "192.0.2.1:1234", "", 401}, {"POST", "/v1/operator/test", "192.0.2.1:1234", "https://other.example.com", 403}, {"GET", "/account/service-tokens", "192.0.2.1:1234", "", 401}} {
if got := request(c.method, c.path, c.peer, c.origin); got != c.status {
t.Fatalf("%s %s: %d", c.method, c.path, got)
}
Expand Down
6 changes: 6 additions & 0 deletions cmd/clawctl-operator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,12 @@ func run(args []string, in io.Reader, out, errOut io.Writer) error {
fmt.Fprintln(errOut, "mcp does not take arguments")
return errUsage
}
if tokenFile != "" {
// Best effort: on failure tools/list stays complete and Hub still enforces.
if self, selfErr := client.ServiceTokenSelf(context.Background()); selfErr == nil && self.Allowlist != nil {
svc.Allowlist = self.Allowlist
}
}
if err := operatoragent.Serve(context.Background(), in, out, svc); err != nil {
fmt.Fprintln(errOut, err.Error())
return err
Expand Down
6 changes: 5 additions & 1 deletion docs/API-SURFACE.md
Original file line number Diff line number Diff line change
Expand Up @@ -845,13 +845,17 @@ Schedule list/get accepts explicitly allowlisted `view`, `operate`, and
`operator-admin` tokens. `view` and `operate` tokens cannot manage schedules.
Catalog approval, revision, preview digest, idempotency and rate-limit checks
still apply to delegated actions.
A valid token (scope, expiry, revocation and source CIDR all pass) calling an
eligible route that is not in its allowlist gets 403 `ROUTE_NOT_ALLOWLISTED`
and does not consume the failed-attempt rate-limit budget. Unknown, revoked or
expired tokens and source-CIDR mismatches keep the generic 401 `UNAUTHENTICATED`.
GET self remains service-token-only. POST rotate is retained as a compatibility route but all service-token scopes are forbidden from using it.

### Service token self and rotation

| Method | Route | Authentication | Response |
| --- | --- | --- | --- |
| GET | `/v1/operator/service-tokens/self` | Current service token only, CIDRs enforced | `id/name/scope/expires_at/max_expiry` (null max means unlimited) |
| GET | `/v1/operator/service-tokens/self` | Current service token only, CIDRs enforced | `id/name/scope/expires_at/max_expiry/allowlist` (null max means unlimited) |
| POST | `/v1/operator/service-tokens/rotate` | Forbidden for all service scopes | 403 `SERVICE_TOKEN_ACTION_FORBIDDEN` |

GET self needs no allowlist entry. POST rotate is a compatibility route and
Expand Down
4 changes: 3 additions & 1 deletion docs/OPERATOR-AUTH.md
Original file line number Diff line number Diff line change
Expand Up @@ -708,7 +708,9 @@ factor failures and internal post-factor failures share the same generic 400 res
only in the creation response; all token responses use `Cache-Control: no-store`.

`GET /v1/operator/service-tokens/self` accepts the current bearer token with
source CIDR checks and returns metadata. The legacy POST rotate route is now
source CIDR checks and returns metadata, including the route allowlist.
`clawctl-operator --token-file … mcp` uses that allowlist to list only the
tools whose Hub routes the token holds. The legacy POST rotate route is now
forbidden for all service scopes (`SERVICE_TOKEN_ACTION_FORBIDDEN`), including
self-rotation. Rotation-chain fields remain for stored-token compatibility.
Humans replace tokens through the MFA-protected creation page, install the new
Expand Down
9 changes: 8 additions & 1 deletion internal/operatoragent/mcp.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func handleMCP(ctx context.Context, svc *Service, payload []byte) (mcpResponse,
case "ping":
return mcpResponse{JSONRPC: "2.0", ID: req.ID, Result: map[string]any{}}, true
case "tools/list":
return mcpResponse{JSONRPC: "2.0", ID: req.ID, Result: map[string]any{"tools": Tools()}}, true
return mcpResponse{JSONRPC: "2.0", ID: req.ID, Result: map[string]any{"tools": svc.tools()}}, true
case "tools/call":
return callTool(ctx, svc, req), true
default:
Expand Down Expand Up @@ -232,3 +232,10 @@ func readMCPMessage(r *bufio.Reader) ([]byte, error) {
}
return body, nil
}

func (s *Service) tools() []Tool {
if s == nil {
return Tools()
}
return ToolsFor(s.Allowlist)
}
115 changes: 115 additions & 0 deletions internal/operatoragent/routes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
package operatoragent

// toolRoutes names every Hub operator route pattern a tool calls. A service
// token sees a tool only when its allowlist holds all of them. Tests keep this
// in step with Tools() and with the Hub's registered routes.
var toolRoutes = map[string][]string{
"signins_list": {"GET /v1/operator/signins"},
"jobs_summary": {"GET /v1/operator/jobs-summary"},
"approvals_summary": {"GET /v1/operator/approvals-summary"},
"loops_list": {"GET /v1/operator/loops"},
"hub_status": {"GET /v1/operator/hub-status"},
"fleet_overview": {"GET /v1/operator/machines"},
"machines_list": {"GET /v1/operator/machines"},
"machine_get": {"GET /v1/operator/machines/{id}"},
"machine_disks": {"GET /v1/operator/machines/{id}/disks"},
"host_profile_get": {"GET /v1/operator/host-profile"},
"join_requests_list": {"GET /v1/operator/joins"},
"machine_readiness": {"GET /v1/operator/machines/{id}/readiness"},
"machine_safe_detail": {"GET /v1/operator/machines/{id}/safe"},
"machine_oom_kills": {"GET /v1/operator/machines/{id}/oom-kills"},
"machine_evidence": {"GET /v1/operator/machines/{id}/evidence"},
"jobs_list": {"GET /v1/operator/jobs"},
"job_get": {"GET /v1/operator/jobs/{id}"},
"job_evidence": {"GET /v1/operator/jobs/{id}/evidence"},
"deployments_list": {"GET /v1/operator/deployments"},
"deployment_get": {"GET /v1/operator/deployments/{id}"},
"software_report": {"GET /v1/operator/software-report"},
"compliance": {"GET /v1/operator/compliance"},
"rollout_status": {"GET /v1/operator/deployments/{id}"},
"rollout_preview": {"POST /v1/operator/deployments/preview"},
"rollout_apply": {"POST /v1/operator/deployments"},
"rollout_expand": {"GET /v1/operator/deployments/{id}", "POST /v1/operator/deployments/{id}/continuations"},
"enroll_ticket_preview": {"POST /v1/operator/enrollment-tokens/preview"},
"enroll_ticket_create": {"POST /v1/operator/enrollment-tokens"},
"deployment_create_preview": {"POST /v1/operator/deployments/preview"},
"deployment_create": {"POST /v1/operator/deployments"},
"deployment_continue_preview": {"POST /v1/operator/deployments/{id}/continuation-preview"},
"deployment_continue": {"GET /v1/operator/deployments/{id}", "POST /v1/operator/deployments/{id}/continuations"},
"deployment_abandon_preview": {"POST /v1/operator/deployments/{id}/abandonment-preview"},
"deployment_abandon": {"POST /v1/operator/deployments/{id}/abandonments"},
"profile_assignment_preview": {"POST /v1/operator/machines/{id}/profile-assignment-preview"},
"profile_assignment_apply": {"POST /v1/operator/machines/{id}/profile-assignments"},
"disk_clean_summaries": {"GET /v1/operator/disk-clean/summaries"},
"disk_clean_summary": {"GET /v1/operator/disk-clean/summaries/{id}"},
"disk_clean_profile_preview": {"POST /v1/operator/disk-clean/profile-preview"},
"disk_clean_profile_publish": {"POST /v1/operator/disk-clean/profiles"},
"disk_clean_dry_run_preview": {"POST /v1/operator/disk-clean/dry-run-preview"},
"disk_clean_dry_run_apply": {"POST /v1/operator/disk-clean/dry-runs"},
"disk_clean_canary_preview": {"POST /v1/operator/disk-clean/canary-preview"},
"disk_clean_canary_apply": {"POST /v1/operator/disk-clean/canaries"},
"disk_clean_continue_preview": {"POST /v1/operator/disk-clean/continuation-preview"},
"disk_clean_continue_apply": {"POST /v1/operator/disk-clean/continuations"},
"disk_clean_abandon_preview": {"POST /v1/operator/disk-clean/abandonment-preview"},
"disk_clean_abandon_apply": {"POST /v1/operator/disk-clean/abandonments"},
"script_catalog_list": {"GET /v1/operator/script-catalog"},
"script_run_preview": {"POST /v1/operator/script-runs/preview"},
"script_run_apply": {"POST /v1/operator/script-runs"},
"schedule_list": {"GET /v1/operator/schedules"},
"schedule_get": {"GET /v1/operator/schedules/{id}"},
"schedule_run_now": {"POST /v1/operator/schedules/{id}/run-now"},
"schedule_job_cancel": {"POST /v1/operator/schedule-jobs/{id}/cancel"},
"schedule_upsert_preview": {"POST /v1/operator/schedules/{operation}/{phase}"},
"schedule_upsert_apply": {"POST /v1/operator/schedules/{operation}/{phase}"},
"schedule_set_enabled_preview": {"POST /v1/operator/schedules/{operation}/{phase}"},
"schedule_set_enabled_apply": {"POST /v1/operator/schedules/{operation}/{phase}"},
"certificate_list": {"GET /v1/operator/certificates"},
"certificate_get": {"GET /v1/operator/certificates/{id}"},
"disk_ops_status": {"GET /v1/operator/disk-ops/status/{machine_id}"},
"disk_report_get": {"GET /v1/operator/disk-ops/reports/{id}"},
"disk_policy_list": {"GET /v1/operator/disk-ops/policies"},
"disk_policy_get": {"GET /v1/operator/disk-ops/policies/{id}"},
"disk_alerts_list": {"GET /v1/operator/disk-ops/alerts"},
"disk_ownership_get": {"GET /v1/operator/disk-ops/ownership/{machine_id}/{scope}"},
"disk_policy_upsert_preview": {"POST /v1/operator/disk-ops/policies/preview"},
"disk_policy_upsert_apply": {"POST /v1/operator/disk-ops/policies"},
"disk_approval_list": {"GET /v1/operator/disk-ops/approvals"},
"disk_approval_decision_preview": {"POST /v1/operator/disk-ops/approvals/{id}/decision/preview"},
"disk_approval_decision_apply": {"POST /v1/operator/disk-ops/approvals/{id}/decision"},
"disk_action_preview": {"POST /v1/operator/disk-ops/actions/preview"},
"disk_action_decide": {"POST /v1/operator/disk-ops/actions/decide"},
"disk_quarantine_list": {"GET /v1/operator/disk-ops/quarantine/{machine_id}"},
"disk_restore_preview": {"POST /v1/operator/disk-ops/restores/preview"},
"disk_restore_apply": {"POST /v1/operator/disk-ops/restores"},
}

// ToolRoutes returns the Hub route patterns tool calls, or nil if unknown.
func ToolRoutes(tool string) []string { return toolRoutes[tool] }

// ToolsFor lists the tools a service token with this allowlist can call. A nil
// allowlist (tailnet identity, no token) lists every tool; Hub still decides.
func ToolsFor(allowlist []string) []Tool {
all := Tools()
if allowlist == nil {
return all
}
allowed := map[string]bool{}
for _, route := range allowlist {
allowed[route] = true
}
out := []Tool{}
next:
for _, tool := range all {
routes := toolRoutes[tool.Name]
if len(routes) == 0 {
continue
}
for _, route := range routes {
if !allowed[route] {
continue next
}
}
out = append(out, tool)
}
return out
}
27 changes: 27 additions & 0 deletions internal/operatoragent/routes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package operatoragent

import (
"context"
"encoding/json"
"strings"
"testing"
)

func TestToolsForFiltersByAllowlist(t *testing.T) {
if len(ToolsFor(nil)) != len(Tools()) {
t.Fatal("nil allowlist must list every tool")
}
got := ToolsFor([]string{"GET /v1/operator/machines", "GET /v1/operator/deployments/{id}"})
names := map[string]bool{}
for _, tool := range got {
names[tool.Name] = true
}
if !names["machines_list"] || !names["fleet_overview"] || !names["rollout_status"] || names["schedule_job_cancel"] || names["rollout_expand"] || len(got) != 4 {
t.Fatalf("filtered tools %v", names)
}
resp, ok := handleMCP(context.Background(), &Service{Allowlist: []string{"GET /v1/operator/hub-status"}}, []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
raw, _ := json.Marshal(resp.Result)
if !ok || !strings.Contains(string(raw), `"hub_status"`) || strings.Contains(string(raw), `"jobs_list"`) {
t.Fatalf("tools/list %s", raw)
}
}
7 changes: 5 additions & 2 deletions internal/operatoragent/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,12 @@ func (e *CallError) Error() string {

// Service calls Hub. A nil Hub fails closed on every call.
// Version is the build version reported by MCP initialize. Empty means dev.
// Allowlist, when non-nil, is the service token's route allowlist and limits
// tools/list to the tools that token can call.
type Service struct {
Hub Hub
Version string
Hub Hub
Version string
Allowlist []string
}

func (s *Service) Call(ctx context.Context, name string, raw json.RawMessage) (any, error) {
Expand Down
1 change: 1 addition & 0 deletions internal/operatorclient/token_rotation.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ type ServiceTokenSelf struct {
Scope string `json:"scope"`
ExpiresAt time.Time `json:"expires_at"`
MaxExpiry *time.Time `json:"max_expiry"`
Allowlist []string `json:"allowlist"`
}

func (c *Client) ServiceTokenSelf(ctx context.Context) (ServiceTokenSelf, error) {
Expand Down
20 changes: 10 additions & 10 deletions internal/store/service_tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import (
)

var ErrServiceToken = errors.New("service token rejected")

// ErrServiceRouteNotAllowed means the token is valid (scope, expiry, source)
// but its route allowlist does not include this route.
var ErrServiceRouteNotAllowed = errors.New("service token route not allowlisted")
var serviceName = regexp.MustCompile(`^[a-zA-Z0-9_-]{1,64}$`)

type ServiceToken struct {
Expand Down Expand Up @@ -227,16 +231,9 @@ func (s *Store) AuthenticateServiceToken(secret, route, peer string, required st
return t, ErrServiceToken
}
}
if len(t.Allowlist) > 0 && route != "GET /v1/operator/service-tokens/self" && route != "POST /v1/operator/service-tokens/rotate" {
found := false
for _, v := range t.Allowlist {
if v == route {
found = true
}
}
if !found {
return t, ErrServiceToken
}
routeAllowed := route == "GET /v1/operator/service-tokens/self" || route == "POST /v1/operator/service-tokens/rotate"
for _, v := range t.Allowlist {
routeAllowed = routeAllowed || v == route
}
if len(t.SourceCIDRs) > 0 {
ip, err := netip.ParseAddr(peer)
Expand All @@ -254,6 +251,9 @@ func (s *Store) AuthenticateServiceToken(secret, route, peer string, required st
return t, ErrServiceToken
}
}
if !routeAllowed {
return t, ErrServiceRouteNotAllowed
}
res, err := (boundExec{s: s, name: "use_service_token"}).Exec(`UPDATE service_tokens SET last_used_at=? WHERE id=? AND revoked_at IS NULL AND (overlap_deadline IS NULL OR julianday(overlap_deadline)>julianday(?)) AND scope=? AND julianday(expires_at)>julianday(?)`, s.now().UTC().Format(time.RFC3339Nano), id, s.now().UTC().Format(time.RFC3339Nano), t.Scope, s.now().UTC().Format(time.RFC3339Nano))
if err != nil {
return ServiceToken{}, err
Expand Down
Loading