route-tester

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

your project Route Tester Skill

你的项目路由测试技能

Purpose

用途

This skill provides patterns for testing authenticated routes in the your project using cookie-based JWT authentication.
本技能提供了使用基于Cookie的JWT认证测试你的项目中已认证路由的相关模式。

When to Use This Skill

适用场景

  • Testing new API endpoints
  • Validating route functionality after changes
  • Debugging authentication issues
  • Testing POST/PUT/DELETE operations
  • Verifying request/response data
  • 测试新的API端点
  • 变更后验证路由功能
  • 调试认证问题
  • 测试POST/PUT/DELETE操作
  • 验证请求/响应数据

your project Authentication Overview

你的项目认证概述

The your project uses:
  • Keycloak for SSO (realm: yourRealm)
  • Cookie-based JWT tokens (not Bearer headers)
  • Cookie name:
    refresh_token
  • JWT signing: Using secret from
    config.ini
你的项目使用:
  • Keycloak 实现SSO(领域:yourRealm)
  • 基于Cookie的JWT 令牌(而非Bearer头)
  • Cookie名称
    refresh_token
  • JWT签名:使用
    config.ini
    中的密钥

Testing Methods

测试方法

Method 1: test-auth-route.js (RECOMMENDED)

方法1:test-auth-route.js(推荐)

The
test-auth-route.js
script handles all authentication complexity automatically.
Location:
/root/git/your project_pre/scripts/test-auth-route.js
test-auth-route.js
脚本会自动处理所有认证相关的复杂操作。
位置
/root/git/your project_pre/scripts/test-auth-route.js

Basic GET Request

基础GET请求

bash
node scripts/test-auth-route.js http://localhost:3000/blog-api/api/endpoint
bash
node scripts/test-auth-route.js http://localhost:3000/blog-api/api/endpoint

POST Request with JSON Data

带JSON数据的POST请求

bash
node scripts/test-auth-route.js \
    http://localhost:3000/blog-api/777/submit \
    POST \
    '{"responses":{"4577":"13295"},"submissionID":5,"stepInstanceId":"11"}'
bash
node scripts/test-auth-route.js \
    http://localhost:3000/blog-api/777/submit \
    POST \
    '{"responses":{"4577":"13295"},"submissionID":5,"stepInstanceId":"11"}'

What the Script Does

脚本功能

  1. Gets a refresh token from Keycloak
    • Username:
      testuser
    • Password:
      testpassword
  2. Signs the token with JWT secret from
    config.ini
  3. Creates cookie header:
    refresh_token=<signed-token>
  4. Makes the authenticated request
  5. Shows the exact curl command to reproduce manually
  1. 从Keycloak获取刷新令牌
    • 用户名:
      testuser
    • 密码:
      testpassword
  2. 使用
    config.ini
    中的JWT密钥对令牌签名
  3. 创建Cookie头:
    refresh_token=<signed-token>
  4. 发送已认证的请求
  5. 显示可手动复现的完整curl命令

Script Output

脚本输出

The script outputs:
  • The request details
  • The response status and body
  • A curl command for manual reproduction
Note: The script is verbose - look for the actual response in the output.
脚本会输出:
  • 请求详情
  • 响应状态和响应体
  • 用于手动复现的curl命令
注意:脚本输出较为详细,请在输出中查找实际的响应内容。

Method 2: Manual curl with Token

方法2:使用令牌手动执行curl

Use the curl command from the test-auth-route.js output:
bash
undefined
使用test-auth-route.js输出中的curl命令:
bash
undefined

The script outputs something like:

脚本会输出类似内容:

💡 To test manually with curl:

💡 如需手动用curl测试:

curl -b "refresh_token=eyJhbGci..." http://localhost:3000/blog-api/api/endpoint

curl -b "refresh_token=eyJhbGci..." http://localhost:3000/blog-api/api/endpoint

Copy and modify that curl command:

复制并修改该curl命令:

curl -X POST http://localhost:3000/blog-api/777/submit
-H "Content-Type: application/json"
-b "refresh_token=<COPY_TOKEN_FROM_SCRIPT_OUTPUT>"
-d '{"your": "data"}'
undefined
curl -X POST http://localhost:3000/blog-api/777/submit
-H "Content-Type: application/json"
-b "refresh_token=<COPY_TOKEN_FROM_SCRIPT_OUTPUT>"
-d '{"your": "data"}'
undefined

Method 3: Mock Authentication (Development Only - EASIEST)

方法3:模拟认证(仅开发环境 - 最简单)

For development, bypass Keycloak entirely using mock auth.
在开发环境中,可完全绕过Keycloak使用模拟认证。

Setup

配置

bash
undefined
bash
undefined

Add to service .env file (e.g., blog-api/.env)

添加到服务的.env文件中(例如:blog-api/.env)

MOCK_AUTH=true MOCK_USER_ID=test-user MOCK_USER_ROLES=admin,operations
undefined
MOCK_AUTH=true MOCK_USER_ID=test-user MOCK_USER_ROLES=admin,operations
undefined

Usage

使用方式

bash
curl -H "X-Mock-Auth: true" \
     -H "X-Mock-User: test-user" \
     -H "X-Mock-Roles: admin,operations" \
     http://localhost:3002/api/protected
bash
curl -H "X-Mock-Auth: true" \
     -H "X-Mock-User: test-user" \
     -H "X-Mock-Roles: admin,operations" \
     http://localhost:3002/api/protected

Mock Auth Requirements

模拟认证要求

Mock auth ONLY works when:
  • NODE_ENV
    is
    development
    or
    test
  • The
    mockAuth
    middleware is added to the route
  • Will NEVER work in production (security feature)
仅在以下情况下模拟认证可用:
  • NODE_ENV
    development
    test
  • 路由已添加
    mockAuth
    中间件
  • 生产环境中绝对不可用(安全特性)

Common Testing Patterns

常见测试模式

Test Form Submission

测试表单提交

bash
node scripts/test-auth-route.js \
    http://localhost:3000/blog-api/777/submit \
    POST \
    '{"responses":{"4577":"13295"},"submissionID":5,"stepInstanceId":"11"}'
bash
node scripts/test-auth-route.js \
    http://localhost:3000/blog-api/777/submit \
    POST \
    '{"responses":{"4577":"13295"},"submissionID":5,"stepInstanceId":"11"}'

Test Workflow Start

测试工作流启动

bash
node scripts/test-auth-route.js \
    http://localhost:3002/api/workflow/start \
    POST \
    '{"workflowCode":"DHS_CLOSEOUT","entityType":"Submission","entityID":123}'
bash
node scripts/test-auth-route.js \
    http://localhost:3002/api/workflow/start \
    POST \
    '{"workflowCode":"DHS_CLOSEOUT","entityType":"Submission","entityID":123}'

Test Workflow Step Completion

测试工作流步骤完成

bash
node scripts/test-auth-route.js \
    http://localhost:3002/api/workflow/step/complete \
    POST \
    '{"stepInstanceID":789,"answers":{"decision":"approved","comments":"Looks good"}}'
bash
node scripts/test-auth-route.js \
    http://localhost:3002/api/workflow/step/complete \
    POST \
    '{"stepInstanceID":789,"answers":{"decision":"approved","comments":"Looks good"}}'

Test GET with Query Parameters

测试带查询参数的GET请求

bash
node scripts/test-auth-route.js \
    "http://localhost:3002/api/workflows?status=active&limit=10"
bash
node scripts/test-auth-route.js \
    "http://localhost:3002/api/workflows?status=active&limit=10"

Test File Upload

测试文件上传

bash
undefined
bash
undefined

Get token from test-auth-route.js first, then:

先从test-auth-route.js获取令牌,然后执行:

curl -X POST http://localhost:5000/upload
-H "Content-Type: multipart/form-data"
-b "refresh_token=<TOKEN>"
-F "file=@/path/to/file.pdf"
-F "metadata={"description":"Test file"}"
undefined
curl -X POST http://localhost:5000/upload
-H "Content-Type: multipart/form-data"
-b "refresh_token=<TOKEN>"
-F "file=@/path/to/file.pdf"
-F "metadata={"description":"Test file"}"
undefined

Hardcoded Test Credentials

硬编码测试凭据

The
test-auth-route.js
script uses these credentials:
  • Username:
    testuser
  • Password:
    testpassword
  • Keycloak URL: From
    config.ini
    (usually
    http://localhost:8081
    )
  • Realm:
    yourRealm
  • Client ID: From
    config.ini
test-auth-route.js
脚本使用以下凭据:
  • 用户名
    testuser
  • 密码
    testpassword
  • Keycloak URL:来自
    config.ini
    (通常为
    http://localhost:8081
  • 领域
    yourRealm
  • 客户端ID:来自
    config.ini

Service Ports

服务端口

Route Prefixes

路由前缀

Check
/src/app.ts
in each service for route prefixes:
typescript
// Example from blog-api/src/app.ts
app.use('/blog-api/api', formRoutes);          // Prefix: /blog-api/api
app.use('/api/workflow', workflowRoutes);  // Prefix: /api/workflow
Full Route = Base URL + Prefix + Route Path
Example:
  • Base:
    http://localhost:3002
  • Prefix:
    /form
  • Route:
    /777/submit
  • Full URL:
    http://localhost:3000/blog-api/777/submit
查看每个服务中的
/src/app.ts
获取路由前缀:
typescript
// 示例来自blog-api/src/app.ts
app.use('/blog-api/api', formRoutes);          // 前缀:/blog-api/api
app.use('/api/workflow', workflowRoutes);  // 前缀:/api/workflow
完整路由 = 基础URL + 前缀 + 路由路径
示例:
  • 基础URL:
    http://localhost:3002
  • 前缀:
    /form
  • 路由:
    /777/submit
  • 完整URL
    http://localhost:3000/blog-api/777/submit

Testing Checklist

测试检查清单

Before testing a route:
  • Identify the service (form, email, users, etc.)
  • Find the correct port
  • Check route prefixes in
    app.ts
  • Construct the full URL
  • Prepare request body (if POST/PUT)
  • Determine authentication method
  • Run the test
  • Verify response status and data
  • Check database changes if applicable
测试路由前:
  • 确定服务(表单、邮件、用户等)
  • 找到正确的端口
  • 检查
    app.ts
    中的路由前缀
  • 构造完整URL
  • 准备请求体(如果是POST/PUT)
  • 确定认证方法
  • 运行测试
  • 验证响应状态和数据
  • 如有需要,检查数据库变更

Verifying Database Changes

验证数据库变更

After testing routes that modify data:
bash
undefined
测试修改数据的路由后:
bash
undefined

SECURITY WARNING: Never pass passwords directly in command line

安全警告:切勿在命令行中直接输入密码

Use secure prompting instead:

请使用安全的输入方式:

Option 1: Use password prompt (recommended)

选项1:使用密码提示(推荐)

docker exec -it local-mysql mysql -u root -p blog_dev
docker exec -it local-mysql mysql -u root -p blog_dev

Option 2: Use environment variable from secure source

选项2:从安全来源获取环境变量

export MYSQL_PWD=$(read -s -p "Enter MySQL root password: " && echo "$REPLY") docker exec -i -e MYSQL_PWD=$MYSQL_PWD local-mysql mysql -u root blog_dev unset MYSQL_PWD
export MYSQL_PWD=$(read -s -p "Enter MySQL root password: " && echo "$REPLY") docker exec -i -e MYSQL_PWD=$MYSQL_PWD local-mysql mysql -u root blog_dev unset MYSQL_PWD

After connecting, check specific table:

连接后,检查特定表:

mysql> SELECT * FROM WorkflowInstance WHERE id = 123; mysql> SELECT * FROM WorkflowStepInstance WHERE instanceId = 123; mysql> SELECT * FROM WorkflowNotification WHERE recipientUserId = 'user-123';
undefined
mysql> SELECT * FROM WorkflowInstance WHERE id = 123; mysql> SELECT * FROM WorkflowStepInstance WHERE instanceId = 123; mysql> SELECT * FROM WorkflowNotification WHERE recipientUserId = 'user-123';
undefined

Debugging Failed Tests

调试失败的测试

401 Unauthorized

401 Unauthorized(未授权)

Possible causes:
  1. Token expired (regenerate with test-auth-route.js)
  2. Incorrect cookie format
  3. JWT secret mismatch
  4. Keycloak not running
Solutions:
bash
undefined
可能原因
  1. 令牌已过期(使用test-auth-route.js重新生成)
  2. Cookie格式不正确
  3. JWT密钥不匹配
  4. Keycloak未运行
解决方法
bash
undefined

Check Keycloak is running

检查Keycloak是否运行

docker ps | grep keycloak
docker ps | grep keycloak

Regenerate token

重新生成令牌

node scripts/test-auth-route.js http://localhost:3002/api/health
node scripts/test-auth-route.js http://localhost:3002/api/health

Verify config.ini has correct jwtSecret

验证config.ini中的jwtSecret是否正确

undefined
undefined

403 Forbidden

403 Forbidden(禁止访问)

Possible causes:
  1. User lacks required role
  2. Resource permissions incorrect
  3. Route requires specific permissions
Solutions:
bash
undefined
可能原因
  1. 用户缺少所需角色
  2. 资源权限配置错误
  3. 路由需要特定权限
解决方法
bash
undefined

Use mock auth with admin role

使用模拟认证并赋予管理员角色

curl -H "X-Mock-Auth: true"
-H "X-Mock-User: test-admin"
-H "X-Mock-Roles: admin"
http://localhost:3002/api/protected
undefined
curl -H "X-Mock-Auth: true"
-H "X-Mock-User: test-admin"
-H "X-Mock-Roles: admin"
http://localhost:3002/api/protected
undefined

404 Not Found

404 Not Found(未找到)

Possible causes:
  1. Incorrect URL
  2. Missing route prefix
  3. Route not registered
Solutions:
  1. Check
    app.ts
    for route prefixes
  2. Verify route registration
  3. Check service is running (
    pm2 list
    )
可能原因
  1. URL不正确
  2. 缺少路由前缀
  3. 路由未注册
解决方法
  1. 检查
    app.ts
    中的路由前缀
  2. 验证路由是否已注册
  3. 检查服务是否运行(
    pm2 list

500 Internal Server Error

500 Internal Server Error(内部服务器错误)

Possible causes:
  1. Database connection issue
  2. Missing required fields
  3. Validation error
  4. Application error
Solutions:
  1. Check service logs (
    pm2 logs <service>
    )
  2. Check Sentry for error details
  3. Verify request body matches expected schema
  4. Check database connectivity
可能原因
  1. 数据库连接问题
  2. 缺少必填字段
  3. 验证错误
  4. 应用程序错误
解决方法
  1. 检查服务日志(
    pm2 logs <service>
  2. 查看Sentry中的错误详情
  3. 验证请求体是否符合预期的Schema
  4. 检查数据库连接性

Using auth-route-tester Agent

使用auth-route-tester Agent

For comprehensive route testing after making changes:
  1. Identify affected routes
  2. Gather route information:
    • Full route path (with prefix)
    • Expected POST data
    • Tables to verify
  3. Invoke auth-route-tester agent
The agent will:
  • Test the route with proper authentication
  • Verify database changes
  • Check response format
  • Report any issues
在进行变更后进行全面的路由测试:
  1. 确定受影响的路由
  2. 收集路由信息
    • 完整路由路径(包含前缀)
    • 预期的POST数据
    • 需要验证的表
  3. 调用auth-route-tester agent
该Agent会:
  • 使用正确的认证方式测试路由
  • 验证数据库变更
  • 检查响应格式
  • 报告任何问题

Example Test Scenarios

示例测试场景

After Creating a New Route

创建新路由后

bash
undefined
bash
undefined

1. Test with valid data

1. 使用有效数据测试

node scripts/test-auth-route.js
http://localhost:3002/api/my-new-route
POST
'{"field1":"value1","field2":"value2"}'
node scripts/test-auth-route.js
http://localhost:3002/api/my-new-route
POST
'{"field1":"value1","field2":"value2"}'

2. Verify database

2. 验证数据库

docker exec -i local-mysql mysql -u root -ppassword1 blog_dev
-e "SELECT * FROM MyTable ORDER BY createdAt DESC LIMIT 1;"
docker exec -i local-mysql mysql -u root -ppassword1 blog_dev
-e "SELECT * FROM MyTable ORDER BY createdAt DESC LIMIT 1;"

3. Test with invalid data

3. 使用无效数据测试

node scripts/test-auth-route.js
http://localhost:3002/api/my-new-route
POST
'{"field1":"invalid"}'
node scripts/test-auth-route.js
http://localhost:3002/api/my-new-route
POST
'{"field1":"invalid"}'

4. Test without authentication

4. 无认证测试

Should return 401

应返回401

undefined
undefined

After Modifying a Route

修改路由后

bash
undefined
bash
undefined

1. Test existing functionality still works

1. 测试现有功能是否仍正常工作

node scripts/test-auth-route.js
http://localhost:3002/api/existing-route
POST
'{"existing":"data"}'
node scripts/test-auth-route.js
http://localhost:3002/api/existing-route
POST
'{"existing":"data"}'

2. Test new functionality

2. 测试新功能

node scripts/test-auth-route.js
http://localhost:3002/api/existing-route
POST
'{"new":"field","existing":"data"}'
node scripts/test-auth-route.js
http://localhost:3002/api/existing-route
POST
'{"new":"field","existing":"data"}'

3. Verify backward compatibility

3. 验证向后兼容性

Test with old request format (if applicable)

(如适用)使用旧的请求格式测试

undefined
undefined

Configuration Files

配置文件

config.ini (each service)

config.ini(每个服务)

ini
[keycloak]
url = http://localhost:8081
realm = yourRealm
clientId = app-client

[jwt]
jwtSecret = your-jwt-secret-here
ini
[keycloak]
url = http://localhost:8081
realm = yourRealm
clientId = app-client

[jwt]
jwtSecret = your-jwt-secret-here

.env (each service)

.env(每个服务)

bash
NODE_ENV=development
MOCK_AUTH=true           # Optional: Enable mock auth
MOCK_USER_ID=test-user   # Optional: Default mock user
MOCK_USER_ROLES=admin    # Optional: Default mock roles
bash
NODE_ENV=development
MOCK_AUTH=true           # 可选:启用模拟认证
MOCK_USER_ID=test-user   # 可选:默认模拟用户
MOCK_USER_ROLES=admin    # 可选:默认模拟角色

Key Files

关键文件

  • /root/git/your project_pre/scripts/test-auth-route.js
    - Main testing script
  • /blog-api/src/app.ts
    - Form service routes
  • /notifications/src/app.ts
    - Email service routes
  • /auth/src/app.ts
    - Users service routes
  • /config.ini
    - Service configuration
  • /.env
    - Environment variables
  • /root/git/your project_pre/scripts/test-auth-route.js
    - 主要测试脚本
  • /blog-api/src/app.ts
    - 表单服务路由
  • /notifications/src/app.ts
    - 邮件服务路由
  • /auth/src/app.ts
    - 用户服务路由
  • /config.ini
    - 服务配置
  • /.env
    - 环境变量

Related Skills

相关技能

  • Use database-verification to verify database changes
  • Use error-tracking to check for captured errors
  • Use workflow-builder for workflow route testing
  • Use notification-sender to verify notifications sent
  • 使用database-verification验证数据库变更
  • 使用error-tracking检查捕获的错误
  • 使用workflow-builder进行工作流路由测试
  • 使用notification-sender验证通知是否发送