Test that an API returns 401 without a token
Call a protected endpoint with no token and with a bad token in one zriz pipeline. Each call must get status 401 and no data.
The problem
A protected endpoint must refuse a call that has no valid token. One wrong line in a route file can open it to all. No error shows this: the endpoint works, also for a stranger.
The test
The example is a shop API. GET /api/auth/me gives the data of the user that the token names.
Start from a project that zz init made: the quick start gives the commands. Add the action me to the resource file.
.zriz/resources/target.json:
{
"type": "http",
"description": "Your app under test",
"base-url": "${env.TARGET_URL}",
"headers": { "Content-Type": "application/json" },
"actions": {
"check": { "method": "GET", "path": "/api/health" },
"me": { "method": "GET", "path": "/api/auth/me" }
}
}
.zriz/pipelines/me-needs-token.json:
{
"description": "No token and a bad token: the API must answer 401",
"steps": [
{
"call": "target/me",
"expect": [
["status", "==", 401],
["body.error", "==", "missing or invalid authorization header"],
["body.email", "not-exists"]
]
},
{
"call": "target/me",
"headers": { "Authorization": "Bearer not-a-real-token" },
"expect": [
["status", "==", 401],
["body.error", "==", "invalid token"],
["body.email", "not-exists"]
]
}
]
}
Run it
zz run me-needs-token
"status":"pass"
What it proves
- The first call,
status == 401: a call with noAuthorizationheader gets no access. - The second call,
status == 401: a token that the API did not make gets no access. body.email not-exists: a refused call gives no user data.
Note: Add one such pipeline for each protected endpoint. The test is short, and a new endpoint is where the fault comes in.
Next
- Test API authorization between two users
- Is zriz safe? tells where your secrets stay.