cybersecurity · beginner · ~15 min

Validate a token against a fixed character allowlist

Strict allow-list + length validation in a single pass.

Challenge

Implement int valid_token(const char *s, size_t min_len, size_t max_len).

Return 1 if all of the following hold:

  • s is non-NULL.
  • strlen(s) is in [min_len, max_len].
  • Every byte of s is in the allow-list [A-Za-z0-9_-].

Return 0 otherwise.

Examples

valid_token("abc123_XYZ-99", 8, 32) -> 1
valid_token("short", 8, 32)         -> 0   // too short
valid_token("has space here", 1, 64)-> 0   // space not allowed
valid_token("ok!", 1, 64)           -> 0   // ! not allowed
valid_token("", 0, 64)              -> 1   // empty allowed when min == 0
valid_token(NULL, 0, 64)            -> 0

Why this matters

API keys, session tokens, and CSRF cookies look random to humans but follow strict rules (e.g. [A-Za-z0-9_-], 32-64 bytes). Validating that a token only contains allow-listed characters before passing it on to anything else is the cheapest defence against injection.

Input format

String + length window.

Output format

1/0.

Constraints

Single pass; no allocations.

Starter code

#include <stddef.h>
int valid_token(const char *s, size_t min_len, size_t max_len) { /* TODO */ return 0; }

Common mistakes

Deny-listing (if (c == ';') return 0;) — infinite holes. Forgetting NULL guard.

Edge cases to handle

Empty input with min==0; min > max; NULL pointer.

Complexity

O(strlen).

Background lessons

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.