Ashrafiucse auth review

From jiayaoqijia/cryptoskill · View interactive version

Ashrafiucse auth review is an AI agent skill from the GitHub repository jiayaoqijia/cryptoskill. Reviews authentication and authorization in any codebase — login flows, password storage, session/cookie handling, JWT pitfalls, OAuth/OIDC misconfigurations, IDOR/broken access control, privilege escalation, CSRF protection, route census for unguarded endpoints, trusted-header identity spoofing, ch

How to use this skill

Skill file

Authentication & Authorization Review

1 — Map the auth architecture first

Find: login/register/password-reset endpoints, session middleware, role/permission checks, token creation/validation, OAuth client configs. Write a 3-line model: who can authenticate how → what identity looks like → where authorization is enforced. Broken access control is much easier to spot once you know the intended model.

Route census (enumerate, don't guess)

Pattern greps find what they look for; a census finds what nobody remembered. Enumerate EVERY route, then check each one:

rg -n "app\.(get|post|put|patch|delete|all|use)\("            # Express/Koa
rg -n "@app\.route\(|@\w+\.route\(|add_url_rule"              # Flask
rg -n "path\(|re_path\(" */urls.py                             # Django
rg -n "^\s*(get|post|patch|put|delete) |resources " config/routes.rb  # Rails
rg -n "@(Get|Post|Put|Patch|Delete|Request)Mapping"             # Spring
rg -n "Route::(get|post|any|resource|apiResource)" routes/     # Laravel
rg -n "@(app|router)\.(get|post|put|delete|patch)"             # FastAPI

Build a table route → auth middleware → ownership check and fill it by reading each handler. Every row with neither is a finding (Critical for admin/state-changing, High otherwise). Census-only catches:

rg -n "req\.(url|originalUrl)\.(startsWith|endsWith|includes|match)|getRequestURI\(\)\.(startsWith|contains|equals)|RAW_URI" -g '*.js' -g '*.ts' -g '*.java' -g '*.py'

the path-matching family: case → encoding → MATCHER STRICTNESS): a

public-path exemption checked with path.endsWith('/x') or

path.contains('/x') instead of an exact/anchored match frees EVERY

colliding route, not just the intended public one (class incident:

Kestra CVE-2026-49869, KEV — AuthenticationFilter used

request.getPath().endsWith("/configs") to whitelist the public

configs endpoint; every namespace-scoped .../configs route bypassed

Basic Auth → unauthenticated API access → RCE). Safe shape: exact

match set (new Set(['/configs']).has(path)) or anchored regex

(^/configs$) — never suffix/substring tests on a path:

rg -n "endsWith\(\s*['\"]\/|\.contains\(\s*['\"]\/" src/ -g '*.java' -g '*.js' -g '*.ts' -g '*.py' | head
rg -n -i "['\"]/(setup|install|installer)[^'\"]*['\"]" -g '*.js' -g '*.ts' -g '*.py' -g '*.java' -g '*.rb' -g '*.php' | head -15
rg -n "rpc \w+\(" -g '*.proto'; rg -n "@GrpcClient|StreamObserver" -g '*.java' -g '*.kt'
rg -n "@(KafkaListener|RabbitListener)|consumer\.|@Scheduled|@CloudFunction|functions\." -g '*.java' -g '*.kt' -g '*.py' -g '*.js' | head

2 — Authentication checks

Password storage

rg -n -i "bcrypt|argon2|scrypt|pbkdf2|md5|sha1|sha256.*password|hashpw|crypt\("

Login mechanics

LDAP authentication (enterprise directories)

rg -n "SECURITY_AUTHENTICATION|ANONYMOUS" -g '*.py' -g '*.java'
rg -n 'uid="\s*\+\s*\w+|SECURITY_PRINCIPAL.*\+' -g '*.py' -g '*.java'
rg -n '\(sAMAccountName=|\(uid=' -g '*.py' -g '*.java'
rg -n "escape_dn_chars|escape_filter_chars|LdapEncoder" -g '*.py' -g '*.java'

Profile changes → account takeover

Email/password-change endpoints are AUTH endpoints — a session alone is not sufficient proof (stolen session, XSS-riding, insider):

rg -n "email\s*=|updateEmail|changeEmail|current_password|currentPassword|change.?password" src/ app/ | head -20

JWT / tokens

rg -n "jwt\.(sign|decode|verify)|verify\(|algorithms|algorithm|none|HS256|RS256"
rg -n "algorithms.*HS256|verify\(.*public|createPublicKey|jwt\.RSAPublicKey" 
rg -n "header\.kid|\bkid\b.*\+|jku|x5u" 

3 — Authorization checks (IDOR & friends)

Find object access points, then check each for an ownership/scope test:

rg -n "req\.params\.id|findById\(|get\(|\.filter\(.*userId|user\.id|currentUser|req\.user"

Mass assignment (generic)

The framework skills cover Laravel/Django/Rails fillable semantics; the generic version bites every ORM:

rg -n "\.create\(\s*req\.body|\.update\(\s*req\.body|Object\.assign\(\s*\w+\s*,\s*req\.body|new \w+\(\s*req\.body|findOneAndUpdate\(\s*\w+,\s*req\.body|bulkCreate\(\s*req\.body"

Request body spread into create/update without an allowlist → attacker sets role, isAdmin, userId, credits, price, email (account takeover via email change). Report High — Critical when the model has role/permission fields. Safe: explicit field destructuring/pick, schema-level allowlist ($fillable, fields), validators configured to strip unknown keys (default validate/zod .strict() — not passthrough). Also check filter/map "sanitizers" that only check types: an allowLIST of keys, not of types, is what counts.

Trusted-header authorization (identity spoofing)

rg -n -i "req\.headers\[\s*['\"]x-|request\.headers\.get\(|getHeader\(\s*\"X-|headers\[\s*'X-|x-forwarded-for|x-forwarded-user|x-real-ip|HTTP_X_"

Using X-User-Id / X-Email / X-Admin / X-Forwarded-For as the identity or authz input means anyone who can reach the service directly is any user → CRITICAL. Valid only when BOTH hold: (1) an edge proxy/gateway strips these headers from inbound traffic, and (2) the app is not directly reachable (check NodePort/LoadBalancer services, ingress annotations, port exposure in compose). Microservice meshes are the classic miss: service B trusts X-User-Id "because only service A calls us" — but anything on the cluster network can. Headers used only for logging (X-Request-Id) are fine — trace the value into an authz decision before flagging.

SSO/OIDC callback host verification (CWE-943). Rocket.Chat GHSL-2026-004/005: an account/SSO service accepted callbacks whose host did not match the configured/allowed one → authentication bypass. Wherever an OIDC/OAuth/SAML/OmniAuth callback or JWKS/discovery URL is resolved from configuration, verify the code checks the exact host/origin (allowlist, not substring/endsWith) and rejects mismatches before trusting the identity assertion → Critical (direct auth bypass).

Authorization predicate on a request-derived principal (sibling of header spoofing — the write side). The capability/role check itself is evaluated against a user object CONSTRUCTED FROM REQUEST DATA instead of the authenticated session principal: user_can(get_user_by('id', $_COOKIE['original_user_id'])), findById(req.cookies.user_id).can(...), hasRole(req.body.role). The check "passes" for whoever the REQUEST names — forging the cookie/param IS the privilege. DevKit Pro CVE-2026-14378 shape: user-switching revert checked manage_options on the cookie-named user instead of current_user_can() → admin takeover. → Critical. The principal for any authz decision must come from the session/token verification path; request data may name a TARGET, never the ACTOR.

rg -n "findById\(\s*req\.(cookies|body|query)|get_user_by\([^)]*\$_(COOKIE|GET|POST|REQUEST)|user_can\s*\(\s*\$" src/ app/ -g '*.js' -g '*.php'

Multi-tenant scoping census (SaaS)

Per-object IDOR checks miss the systematic version: in a multi-tenant app, EVERY data access must carry the tenant filter — one query without it leaks a whole tenant's data to another tenant's users (often via list/export/report endpoints that feel "shared").

rg -n "tenant|org_?id|account_?id|customer_?id|workspace" -g '*.js' -g '*.ts' -g '*.py' -g '*.java' -g '*.rb' -g '*.php'   # tenant model census — size it (wc -l), then read
rg -n "\.(find|where|filter|all|select|query|get)(All)?\(" -g '*.js' -g '*.py' | rg -v "tenant|org_|account_|customer_|user"   # unscoped reads — census: disposition EVERY line

Method: list every model access, mark each SCOPED (tenant filter present) / UNSCOPED / GLOBAL-BY-DESIGN (shared catalog). Every UNSCOPED access to tenant-owned data → Critical. Stronger defenses to note when present: DB-level row-level security (RLS), ORM global scopes (Laravel global scope, Django manager), middleware-injected tenant context that queries MUST use. Also check: tenant taken from request body/header instead of session (req.body.tenantId — attacker-controlled scope switch → cross-tenant, Critical), and cache keys missing the tenant prefix (cross-tenant cache bleed).

a request names a TARGET (user_id, email, login_name) and the

handler issues enrollment codes / invitations / reset URLs / passkey or

passwordless registrations for that target, checking only the CALLER's

request tenant (org header, subdomain) while never comparing the

TARGET's tenant = cross-tenant takeover: an admin (or any

user-write holder) in org A obtains enrollment credentials for org-B

users and registers their own authenticator (class incident: ZITADEL

CVE-2026-105209 — passkey enrollment codes authorized against

x-zitadel-orgid while the target user's organization went unchecked,

cross-org ATO, CVSS 9.6). The authz must compare the TARGET's tenant

with the caller's tenant (or verify the caller's scope covers the

target's tenant) — validating the request's own tenant header proves

nothing about the target. Strongest shape: scope the target lookup itself

by the caller's session tenant (findOne({ id, org_id: session.org }))

rather than fetch-then-check:

rg -n -i "enroll(ment)?.?code|invite.?(code|user)|passwordless" src/ app/ -g '*.js' -g '*.ts' -g '*.py' -g '*.java' | head

Check-then-act races (TOCTOU)

Look for state checks followed by a separate write:

rg -n "if\s*\(.*\b(used|redeemed|approved|active|enabled|stock|balance|remaining)\b|\.findOne\(.*\)\.then|SELECT.*\b(balance|stock|used)\b.*FROM|\.save\(\)"

Feature-flag & plan-capability gating

Flags constrain CAPABILITY (what a plan/tenant/role may do), not identity — an authenticated admin can still be the attacker the plan must stop. UI/menu gating is cosmetic; the handler/route is the enforcement point. Incident class (2026-09-23): a trial tenant blasted 1200+ emails through a compose route whose flag was enforced only in the menu and the queued job.

rg -n "Feature::(define|active)|isFeatureEnabled|featureFlags|feature_flags|isEnabled\(|isEnabledFor|\.variation\(" src/ app/ modules/
rg -n "pennant:purge|flushCache|flag.*purge" deploy/ scripts/ .github/

Stack-agnostic census (framework skills carry the concrete greps — e.g. ../laravel-security/SKILL.md Step 8):

One-time codes (verification / login / MFA codes)

A one-time code IS a bearer credential — census every endpoint that PRODUCES or VERIFIES one, then check WHERE the code goes and WHAT ELSE the verifier accepts:

rg -n -i "verification.?code|login.?code|one[-_ ]?time.?code|\botp\b|magic.?code|sms.?code|email.?code" src/ app/ routes/ | head -40
rg -n -i "(master|static|backdoor|debug|test).{0,12}code" src/ app/ config/ db/ seeds/ -g '*.sql' -g '*.java' -g '*.py' -g '*.js' -g '*.ts' -g '*.yml'

Webhook receiver authentication

Webhook endpoints are authenticated by the SENDER's signature, not by your sessions — an unverified receiver is an unauthenticated endpoint with money/entitlement powers. Census every webhook/callback route with §1's table, then:

rg -n "webhook|callback" src/ app/ routes/ | rg -i "post|route" | head -20
rg -n "timingSafeEqual|compare_digest|verify_sig|verifySignature|signature" src/ app/
rg -n "!process\.env\.[A-Z_]*SECRET|WEBHOOK_SECRET" src/ app/ .env.example 2>/dev/null
rg -n "wp_set_auth_cookie\s*\(|wp_set_current_user\s*\(|req\.login\s*\(|\.logIn\s*\(" src/ app/ -g '*.js' -g '*.ts' -g '*.php'

API keys as authentication (service-to-service)

Machine auth has its own failure modes — check every API-key/gateway-token scheme:

rg -n -i "x-api-key|api[_-]?key" -g '*.js' -g '*.ts' -g '*.py' -g '*.java' -g '*.go' -g '*.rb' | head
rg -n -i "findby(hostname|serial|hardware)|by_(hostname|serial)|token\s*={2,3}[^=]*(hostname|serial|machine.?id)" -g '*.js' -g '*.ts' -g '*.py' -g '*.go' -g '*.java'
rg -n -i "internal[_-]?key|x-internal|internal[_-]?api[_-]?key" src/ app/ -g '*.js' -g '*.ts' -g '*.py' -g '*.java'

4 — Session & CSRF

5 — OAuth/OIDC, if present

verification**: census every surface that BINDS an external-IdP identity

to a local account (AddIDPLink, /auth/link, link_account, social

connect). A linking call that acts on a caller-SUPPLIED login name /

user identifier — without an authenticated session plus a fresh primary

factor or proof of control of BOTH identities — lets anyone who knows a

victim's login name attach their OWN IdP identity and then sign in as the

victim (class incident: ZITADEL CVE-2026-105207 — User Service V2

AddIDPLink + identify-only Login V2 sessions, unauthenticated ATO,

CVSS 9.8). → Critical. Safe shape: link only to the session principal,

require step-up re-auth, and take the external identity from the IdP's

verified assertion (never from request fields):

rg -n -i "add_?idp|idp.?link|link.?(account|identity)|connect.?(account|identity)" src/ app/ -g '*.js' -g '*.ts' -g '*.py' -g '*.java' -g '*.go' -g '*.php' | head -20

Host-header poisoning in outbound auth/email flows

Password-reset/verification links and OAuth redirect URIs built from Host / X-Forwarded-Host (request-derived) let an attacker poison the victim's link domain (CodeQL class; Django's ALLOWED_HOSTS=['*'] is the classic enabler — see ../django-security/SKILL.md Step 1). Grep link/URL construction in mailers and auth controllers for request-header inputs → HIGH (account takeover via poisoned reset links).

6 — SAML (if present)

rg -n -i "saml|assertion|NameID|acs[ _-]?url|AudienceRecipient|samlp" -g '*.py' -g '*.java' -g '*.rb' -g '*.php' -g '*.js' -g '*.xml' | head -15

The four classic SAML bugs, in observed frequency order:

Safe shapes: pinned ACS + audience, both signed flags true, one-assertion-only, tight skew (≤5m), library current (python3-saml / OneLogin / passport-saml families each had historic CVEs — version-check via vuln-db/OSV).

7 — Realtime channels (WebSocket / SSE)

rg -n "io\.on\(|socket\.on\(|new WebSocket|WebSocketServer|@MessageMapping|@SubscribeMapping|STOMP|EventSource|ActionCable|cable\.|channel\.subscribe"
rg -n "socket\.on\(\s*['\"][^'\"]*(command|cmd|exec|run)|@MessageMapping\(\s*['\"][^'\"]*(command|cmd|exec)" src/ app/ -g '*.js' -g '*.ts' -g '*.java'
rg -n "(agent|host)\.(send|execute|invoke)\(" src/ app/ | head

Reporting

For each finding: severity, file:line, one-line exploit story ("authenticated user A reads user B's invoice by changing ?id="), and the concrete fix (ownership scope in query, middleware, flag). Group IDORs by endpoint pattern — they usually cluster.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.