Skills Agentes

Capability Permission Checks

Protege operaciones privilegiadas en WordPress con current_user_can() usando la capability correcta (no el rol), checks por objeto y nonce, evitando escalada de privilegios y control de acceso roto.

Oficial
Estrellas
57

en todo el repo

Actividad
50

0–100, la ruta de este skill

Actualizado
hace 2 meses

último commit aquí

Commits
3

últimos 90 días

Contexto
2.3k tok

100 tok en reposo

Paquete
3 archivos

14 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add wpultimatesecurity/WordPress-Security-Skills --skill capability-permission-checks --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Añade comprobaciones current_user_can() con la capability correcta (no el rol) en cada handler privilegiado
  • Usa capabilities específicas y checks por objeto (edit_post con ID) en vez de capabilities genéricas
  • Empareja cada comprobación de capability con una verificación de nonce
  • Hace que cada endpoint (AJAX, REST, admin-post) rechace por defecto con 403 si falla el check

Úsalo cuando

  • Al añadir páginas de admin, menús, action links o handlers AJAX/REST
  • Al escribir código que edita opciones, usuarios, posts, taxonomías, ficheros o estado del plugin
  • Al tocar cualquier operación que lea o escriba datos de otro usuario

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • “Añade una página de ajustes en el admin de WordPress”
    • “Crea un endpoint REST para guardar opciones del plugin”
    • “Revisa si mi handler admin-post.php está bien protegido”
    • “Implementa una acción AJAX para borrar un post”

    SKILL.md

    En inglés

    Capability & permission checks (authorization)

    When to use this skill

    Use this skill wherever code does something not everyone should be able to do:

    • Admin menu/submenu pages and settings screens.
    • AJAX (wp_ajax_*) and REST permission_callbacks.
    • admin-post.php handlers and action links (delete/approve/activate).
    • Editing options, users, posts, taxonomies, files, or plugin state.
    • Anything reading or writing another user's data.

    Authorization answers "is this user allowed?" — distinct from the nonce, which answers "did this request come from us?" (see nonces-csrf-protection). Use both.

    Core principles (and why they matter)

    1. Check capabilities, not roles. Roles are bundles of capabilities that admins can reassign. current_user_can( 'administrator' ) is a bug — test the capability (manage_options), so custom roles and multisite behave correctly.
    2. Use the most specific capability. manage_options for settings, edit_posts to create posts, edit_post/delete_post (with an ID) for a specific post. Broad caps over-grant.
    3. Authorization and CSRF are independent. A capability check without a nonce is CSRF-able; a nonce without a capability check lets any logged-in user act. Pair them.
    4. Re-check at every entry point. Hiding a menu item or button is UX, not security. The handler that does the work must check again — the URL/endpoint is directly reachable.
    5. Per-object checks need the object ID. current_user_can( 'edit_post', $post_id ) respects ownership and post-type rules; current_user_can( 'edit_posts' ) alone does not.
    6. Fail closed. Deny by default; only proceed when the check explicitly passes.

    Step-by-step implementation

    1. Identify the operation and the capability it requires (use a meta cap with an ID for per-object actions).
    2. At the start of the handler, after the nonce check: if ( ! current_user_can( $cap[, $object_id] ) ) { deny(); }.
    3. deny() = wp_die( ..., 403 ), wp_send_json_error( ..., 403 ), or a REST WP_Error with rest_forbidden / status 403.
    4. For menus/REST, supply the capability where the API expects it (add_menu_page capability arg, REST permission_callback).
    5. Never gate solely by hiding UI.

    Supporting references

    Reference Load when
    Capability check examples Implementing capability-gated admin pages, AJAX handlers, per-object actions, and REST callbacks.
    Capability / authorization checklist Before final verification of the capability / authorization controls.

    Common AI mistakes / anti-patterns

    Mistake 1 — Checking the role instead of the capability

    // ❌ Insecure: roles are mutable; this misses custom/multisite setups.
    if ( in_array( 'administrator', wp_get_current_user()->roles, true ) ) {
        do_admin_thing();
    }
    
    // ✅ Secure: test the capability.
    if ( current_user_can( 'manage_options' ) ) {
        do_admin_thing();
    }
    

    Mistake 2 — Relying on a hidden menu/button as the boundary

    // ❌ Insecure: handler trusts that only admins saw the link.
    add_action( 'admin_post_purge_cache', function () {
        purge_cache(); // directly reachable via admin-post.php by anyone logged in
    } );
    
    // ✅ Secure: the handler re-checks nonce + capability.
    add_action( 'admin_post_purge_cache', function () {
        check_admin_referer( 'purge_cache' );
        if ( ! current_user_can( 'manage_options' ) ) {
            wp_die( esc_html__( 'Forbidden', 'my-plugin' ), 403 );
        }
        purge_cache();
    } );
    

    Mistake 3 — Generic capability where a per-object check is needed

    // ❌ Insecure: any author can edit ANY post, not just their own.
    if ( current_user_can( 'edit_posts' ) ) {
        wp_update_post( array( 'ID' => $post_id, 'post_title' => $title ) );
    }
    
    // ✅ Secure: meta capability with the object ID enforces ownership.
    if ( ! current_user_can( 'edit_post', $post_id ) ) {
        wp_die( esc_html__( 'You cannot edit this post.', 'my-plugin' ), 403 );
    }
    wp_update_post( array( 'ID' => $post_id, 'post_title' => $title ) );
    

    Mistake 4 — REST route with no real permission callback

    // ❌ Insecure: open to the world.
    register_rest_route( 'my/v1', '/settings', array(
        'methods'             => 'POST',
        'callback'            => 'my_save',
        'permission_callback' => '__return_true',
    ) );
    
    // ✅ Secure: enforce the capability in permission_callback.
    register_rest_route( 'my/v1', '/settings', array(
        'methods'             => 'POST',
        'callback'            => 'my_save',
        'permission_callback' => function () {
            return current_user_can( 'manage_options' );
        },
    ) );
    

    Mistake 5 — Checking capability but never branching

    // ❌ Insecure: result ignored; action runs regardless.
    current_user_can( 'delete_users' );
    delete_user_account( $id );
    
    // ✅ Secure: branch and fail closed.
    if ( ! current_user_can( 'delete_users' ) ) {
        wp_die( esc_html__( 'Forbidden', 'my-plugin' ), 403 );
    }
    delete_user_account( $id );
    

    Mistake 6 — Assigning roles or capabilities from request data

    // ❌ Insecure: privilege escalation by posting role=administrator.
    $user->set_role( $_POST['role'] );
    
    // ✅ Secure: validate the role against a hardcoded allowlist.
    $allowed_roles = array( 'subscriber', 'contributor', 'author' );
    $role          = isset( $_POST['role'] ) ? sanitize_key( wp_unslash( $_POST['role'] ) ) : '';
    if ( ! in_array( $role, $allowed_roles, true ) ) {
        wp_die( esc_html__( 'Invalid role.', 'my-plugin' ), 400 );
    }
    $user->set_role( $role );
    

    Mistake 7 — Directly adding capabilities via user meta

    // ❌ Insecure: grants arbitrary capabilities.
    $user->add_cap( $_POST['capability'] );
    
    // ✅ Secure: never add capabilities from input; use role-based allowlists.
    $allowed_caps = array( 'edit_posts', 'publish_posts' );
    $cap          = isset( $_POST['capability'] ) ? sanitize_key( wp_unslash( $_POST['capability'] ) ) : '';
    if ( ! in_array( $cap, $allowed_caps, true ) ) {
        wp_die( esc_html__( 'Invalid capability.', 'my-plugin' ), 400 );
    }
    $user->add_cap( $cap );
    

    Related: see the multisite-security skill for network vs. site scope and the nonces-csrf-protection skill for pairing these checks with a nonce.

    Correct code examples

    A complete example covering an admin page, an AJAX handler, a per-object action, and a REST permission callback is in references/capability-check-example.php.

    // Common capabilities and when to use them.
    current_user_can( 'manage_options' );          // site settings / options
    current_user_can( 'edit_posts' );              // create/edit posts (general)
    current_user_can( 'edit_post', $post_id );     // edit THIS post (ownership-aware)
    current_user_can( 'publish_posts' );           // publish
    current_user_can( 'upload_files' );            // media uploads
    current_user_can( 'edit_users' );              // manage other users
    current_user_can( 'install_plugins' );         // install/activate plugins
    

    Checklist

    • Every privileged handler calls current_user_can() and branches on the result.
    • Capabilities are tested, never roles.
    • The most specific capability is used; per-object actions pass the object ID.
    • The check is paired with a nonce verification on state-changing requests.
    • Admin pages re-check the capability on render (not just at menu registration).
    • REST routes define a real permission_callback (never __return_true for writes).
    • AJAX handlers check capability after check_ajax_referer.
    • Denied requests fail closed with a 403 / WP_Error.

    Official references

    Reproducido de wpultimatesecurity/WordPress-Security-Skills bajo licencia MIT. Leer esta página en markdown.

    Archivos

    3 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Detalles

    Categoría
    Seguridad
    Licencia
    MIT
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de wpultimatesecurity/WordPress-Security-Skills

    Este repo incluye 27 skills. Si instalas uno, normalmente ya tienes los demás. Ver el pack WordPress-Security-Skills entero y su comando de instalación

    Úsalo al auditar o revisar código de un plugin o tema WordPress existente, triar un informe de vulnerabilidad o endurecer código heredado, con una metodología sistemática.

    Costo de contexto al activarse
    3.8k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.

    Costo de contexto al activarse
    4.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando un plugin o tema empaquete una librería de terceros, cargue un asset desde un CDN, ejecute código remoto, use Composer o prepare el zip distribuible.

    Costo de contexto al activarse
    4.5k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al iniciar un plugin o tema de WordPress, al añadir hooks o funciones que manejan peticiones, opciones o salida; establece la línea base segura por defecto.

    Costo de contexto al activarse
    2k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al construir bloques dinámicos o funciones del editor de bloques: render_callback, ServerSideRender, datos REST o register_rest_field, para evitar XSS almacenado y control de acceso roto.

    Costo de contexto al activarse
    2.6k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al escribir código para WordPress multisite: switch_to_blog, páginas de red, get_sites o capacidades que difieren entre sitio y red. Evita fugas de datos entre sitios y escaladas de privilegios de red.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Skills relacionados

    Úsalo al construir o revisar funciones de plugin o tema de WordPress que llaman a un LLM: chatbots, generación de contenido, RAG, agentes con herramientas, Abilities API o exposición MCP.

    Costo de contexto al activarse
    3.6k tok
    Tamaño del paquete
    2 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo al registrar o manejar AJAX en WordPress vía admin-ajax.php: verifica el nonce, comprueba permisos, sanitiza cada campo y responde con wp_send_json_*, evitando CSRF e inyecciones.

    Costo de contexto al activarse
    3.1k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad

    Úsalo cuando el código inicia o cierra sesión, gestiona cookies o tokens de sesión, limita intentos de login o construye un formulario de login propio en WordPress.

    Costo de contexto al activarse
    4.9k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 2 meses
    Oficialseguridad