Skip to content

Agent auth middleware: resolve bearer tokens → agent context #854

@chubes4

Description

@chubes4

Context

Phase 2 of agent runtime authentication (#740). Phase 1 (PR #853) added the token CRUD layer — datamachine_agent_tokens table with create/revoke/list via abilities, CLI, and REST.

This phase adds the middleware that actually authenticates incoming requests using those tokens.

What to Build

inc/Core/Auth/AgentAuthMiddleware.php (new file)

Hooks rest_authentication_errors filter — runs before any permission_callback.

Flow:

  1. Check Authorization header for Bearer datamachine_* prefix
  2. hash('sha256', $token) → lookup in datamachine_agent_tokens via AgentTokens::resolve_token()
  3. Validate: token not expired, agent is active (status = 'active'), owner user is active
  4. AgentTokens::touch_last_used() — track usage
  5. wp_set_current_user($owner_id) — WordPress sees the owner (for WP cap checks)
  6. PermissionHelper::set_agent_context($agent_id, $owner_id, $token_capabilities) — set agent scope
  7. Return true (authenticated) — all subsequent permission_callback checks run with agent context

Security:

  • Only intercepts tokens with datamachine_ prefix — does not interfere with other auth mechanisms
  • Token hash lookup is O(1) via UNIQUE index
  • Must not interfere with existing WordPress Application Passwords or cookie auth
  • Non-matching Authorization headers pass through to WordPress's normal auth chain

data-machine.php changes

Register the middleware on init or rest_api_init:

new \DataMachine\Core\Auth\AgentAuthMiddleware();

Depends On

Related

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions