Secure Coding and Application Security Questions
Writing and reviewing code that resists attack. Covers the OWASP Top Ten and common web vulnerabilities (XSS, SQL injection, CSRF), input validation, secure coding practices and security code review, static application security testing (SAST), API and HTTP security, database and frontend security, and mobile app security. The application-layer defense discipline for engineers building software.
Design a database schema and server-side logic for refresh-token rotation with reuse detection. Requirements: when a refresh token is used it is immediately rotated and the old token becomes invalid; if a previously-rotated (replayed) token is used, mark the session as compromised and revoke all related tokens. Describe the schema fields, the transactional operations needed to prevent race conditions on concurrent refresh attempts, and the cleanup procedure for expired tokens.
Sample Answer
Direct answer
The schema needs one row per issued refresh token, not one row per session, with a chain pointer (replaced_by) linking each token to the token that rotated it: a token used once has that pointer set, and a token presented a second time (meaning its pointer is already set) is unambiguous proof of replay, since a legitimate client only ever presents the newest unused token in the chain. Every rotation is one atomic transaction: look the token up, check its state, and either rotate it or flip the whole session to compromised, all inside a single database transaction so two callers racing on the same token cannot both believe they won.
Structured elaboration
Approach. Two tables: sessions (one row per logical login) and refresh_tokens (one row per issued token, chained by rotation). Rotation, replay detection, and the race-prevention mechanism all fall out of a single rule applied consistently: a refresh token is valid to redeem exactly once, and the transaction that redeems it is the same transaction that determines whether it was already redeemed.
Schema.
CREATE TABLE sessions (
id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
created_at TIMESTAMP NOT NULL,
status TEXT NOT NULL CHECK (status IN ('active','compromised','revoked'))
);
CREATE TABLE refresh_tokens (
id TEXT PRIMARY KEY,
session_id TEXT NOT NULL REFERENCES sessions(id),
token_hash TEXT NOT NULL, -- hash of the token secret, never the raw secret
created_at TIMESTAMP NOT NULL,
expires_at TIMESTAMP NOT NULL,
replaced_by TEXT NULL, -- set the moment this token is rotated
revoked BOOLEAN NOT NULL DEFAULT FALSE,
used_at TIMESTAMP NULL
);
CREATE INDEX idx_rt_hash ON refresh_tokens(token_hash);
token_hash, not the raw token: if the database is ever read (backup leak, insider access, a misconfigured replica), the stored value is useless to an attacker on its own, the same reasoning as password hashing.replaced_byis the entire reuse-detection mechanism: null means "this is the current, valid token for the session"; non-null means "this token was already redeemed once, and its replacement's id is here."sessions.statusis the blast-radius control: a single compromise finding flips the whole session, not just one token, because once a rotated token has been replayed, the attacker plausibly also has (or will present) other tokens from the same chain.
Transactional operation (the actual rotate-or-detect logic).
-- one transaction, one round trip, using a write lock on the token row so
-- a concurrent rotation attempt cannot interleave
BEGIN IMMEDIATE; -- SQLite's write-lock-for-the-transaction; the Postgres
-- equivalent is SELECT ... FOR UPDATE on the token row
SELECT id, session_id, expires_at, replaced_by, revoked
FROM refresh_tokens WHERE token_hash = :presented_hash;
-- not found / revoked / expired -> reject and ROLLBACK
-- if replaced_by IS NOT NULL: this exact token was already redeemed once.
-- A second presentation of it is either an attacker replaying a copy they
-- captured, or (see Trade-offs) a client-side double-submission race.
-- Either way, the token chain cannot distinguish the two, so it is treated
-- as compromise:
UPDATE sessions SET status = 'compromised' WHERE id = :session_id;
UPDATE refresh_tokens SET revoked = TRUE WHERE session_id = :session_id;
COMMIT;
-- return 403, force full re-authentication
-- otherwise (replaced_by IS NULL, token is genuinely fresh): rotate
INSERT INTO refresh_tokens (id, session_id, token_hash, created_at, expires_at)
VALUES (:new_id, :session_id, :new_hash, now(), :new_expiry);
UPDATE refresh_tokens
SET used_at = now(), replaced_by = :new_id
WHERE id = :old_id;
COMMIT;
-- return the new refresh token (raw secret) + a fresh short-lived access token
Concurrency and race prevention. BEGIN IMMEDIATE (SQLite) or SELECT ... FOR UPDATE (Postgres) on the token row means the entire lookup-check-rotate sequence for one token is serialized against any other transaction trying to touch the same row: whichever request's transaction commits first "wins" the rotation, and the loser's transaction, once it can proceed, re-reads the row and now sees replaced_by already set, exactly as if it had presented an already-rotated token. There is no window where both requests can independently believe they were first, because the database's own locking makes that outcome impossible, not application logic that could itself have a bug.
Cleanup. A background job periodically deletes rows past their usefulness for both storage growth and forensic retention:
DELETE FROM refresh_tokens WHERE expires_at < now();
Rows are kept for a short retention window past expiry (rather than deleted the instant a token is spent) specifically so a delayed forensic investigation can still see the rotation chain that led to a compromise finding.
Worked example
The schema and transaction logic above are executed, not just described, with sqlite3 (Python standard library, no external services) standing in for the transactional database. BEGIN IMMEDIATE reproduces the write-lock semantics SELECT ... FOR UPDATE would give in Postgres, on a single database file.
import sqlite3
import threading
import time
import uuid
import hashlib
from datetime import datetime, timedelta, timezone
DB_PATH = "/tmp/s79_refresh_rotation_demo.db"
def fresh_db():
conn = sqlite3.connect(DB_PATH, timeout=10, isolation_level=None)
conn.execute("PRAGMA foreign_keys = ON")
conn.executescript(
"""
DROP TABLE IF EXISTS refresh_tokens;
DROP TABLE IF EXISTS sessions;
CREATE TABLE sessions (
id TEXT PRIMARY KEY, user_id TEXT NOT NULL, created_at TEXT NOT NULL,
status TEXT NOT NULL CHECK (status IN ('active','compromised','revoked'))
);
CREATE TABLE refresh_tokens (
id TEXT PRIMARY KEY, session_id TEXT NOT NULL REFERENCES sessions(id),
token_hash TEXT NOT NULL, created_at TEXT NOT NULL, expires_at TEXT NOT NULL,
replaced_by TEXT, revoked INTEGER NOT NULL DEFAULT 0, used_at TEXT
);
CREATE INDEX idx_rt_hash ON refresh_tokens(token_hash);
"""
)
return conn
def now_iso():
return datetime.now(timezone.utc).isoformat()
def hash_token(secret: str) -> str:
return hashlib.sha256(secret.encode()).hexdigest()
def seed_session_with_token(conn, secret: str, ttl_minutes=43200):
session_id, token_id = str(uuid.uuid4()), str(uuid.uuid4())
conn.execute("BEGIN IMMEDIATE")
conn.execute("INSERT INTO sessions (id, user_id, created_at, status) VALUES (?,?,?,?)",
(session_id, "user-1", now_iso(), "active"))
conn.execute(
"INSERT INTO refresh_tokens (id, session_id, token_hash, created_at, expires_at) VALUES (?,?,?,?,?)",
(token_id, session_id, hash_token(secret), now_iso(),
(datetime.now(timezone.utc) + timedelta(minutes=ttl_minutes)).isoformat()))
conn.commit()
return session_id, token_id
class ReplayDetected(Exception): pass
class TokenInvalid(Exception): pass
def rotate_token(conn: sqlite3.Connection, presented_secret: str, retries=5):
h = hash_token(presented_secret)
for attempt in range(retries):
try:
conn.execute("BEGIN IMMEDIATE")
break
except sqlite3.OperationalError as e:
if "locked" in str(e) and attempt < retries - 1:
time.sleep(0.05); continue
raise
try:
row = conn.execute(
"SELECT id, session_id, expires_at, replaced_by, revoked FROM refresh_tokens WHERE token_hash = ?",
(h,)).fetchone()
if row is None:
conn.rollback(); raise TokenInvalid("no such token")
token_id, session_id, expires_at, replaced_by, revoked = row
if revoked:
conn.rollback(); raise TokenInvalid("token revoked")
if datetime.fromisoformat(expires_at) < datetime.now(timezone.utc):
conn.rollback(); raise TokenInvalid("token expired")
if replaced_by is not None:
conn.execute("UPDATE sessions SET status = 'compromised' WHERE id = ?", (session_id,))
conn.execute("UPDATE refresh_tokens SET revoked = 1 WHERE session_id = ?", (session_id,))
conn.commit()
raise ReplayDetected(f"session {session_id} marked compromised, all tokens revoked")
new_secret, new_id = str(uuid.uuid4()), str(uuid.uuid4())
conn.execute(
"INSERT INTO refresh_tokens (id, session_id, token_hash, created_at, expires_at) VALUES (?,?,?,?,?)",
(new_id, session_id, hash_token(new_secret), now_iso(),
(datetime.now(timezone.utc) + timedelta(minutes=43200)).isoformat()))
conn.execute("UPDATE refresh_tokens SET used_at = ?, replaced_by = ? WHERE id = ?",
(now_iso(), new_id, token_id))
conn.commit()
return new_secret
except (ReplayDetected, TokenInvalid):
raise
except Exception:
conn.rollback(); raise
def scenario_1_normal_rotation():
conn = fresh_db()
session_id, _ = seed_session_with_token(conn, "secret-A")
new_secret = rotate_token(conn, "secret-A")
assert new_secret is not None
assert conn.execute("SELECT status FROM sessions WHERE id=?", (session_id,)).fetchone()[0] == "active"
newer_secret = rotate_token(conn, new_secret)
assert newer_secret != new_secret
conn.close()
print("[1] normal rotation: OK (two sequential rotations succeeded, session stayed active)")
def scenario_2_replay_detected():
conn = fresh_db()
session_id, _ = seed_session_with_token(conn, "secret-B")
rotate_token(conn, "secret-B")
try:
rotate_token(conn, "secret-B")
raise SystemExit("expected ReplayDetected, got none")
except ReplayDetected as e:
print(f"[2] replay detected as expected: {e}")
status = conn.execute("SELECT status FROM sessions WHERE id=?", (session_id,)).fetchone()[0]
revoked_count = conn.execute("SELECT COUNT(*) FROM refresh_tokens WHERE session_id=? AND revoked=1",
(session_id,)).fetchone()[0]
total_count = conn.execute("SELECT COUNT(*) FROM refresh_tokens WHERE session_id=?",
(session_id,)).fetchone()[0]
assert status == "compromised"
assert revoked_count == total_count == 2
print(f" session status={status}, {revoked_count}/{total_count} tokens revoked")
def scenario_3_concurrent_race():
conn_seed = fresh_db()
session_id, _ = seed_session_with_token(conn_seed, "secret-C")
conn_seed.close()
results = {}
def worker(name):
conn = sqlite3.connect(DB_PATH, timeout=10, isolation_level=None)
try:
new_secret = rotate_token(conn, "secret-C")
results[name] = ("rotated", new_secret)
except ReplayDetected as e:
results[name] = ("replay", str(e))
except TokenInvalid as e:
results[name] = ("invalid", str(e))
finally:
conn.close()
t1, t2 = threading.Thread(target=worker, args=("t1",)), threading.Thread(target=worker, args=("t2",))
t1.start(); t2.start(); t1.join(); t2.join()
outcomes = sorted(v[0] for v in results.values())
print(f"[3] concurrent race on the same still-valid token: outcomes = {results}")
assert outcomes == ["replay", "rotated"], f"expected one rotate + one replay, got {outcomes}"
conn = sqlite3.connect(DB_PATH)
status = conn.execute("SELECT status FROM sessions WHERE id=?", (session_id,)).fetchone()[0]
print(f" session status after the race: {status} <- the false-positive compromise call-out in the answer")
conn.close()
def scenario_4_cleanup():
conn = fresh_db()
session_id = str(uuid.uuid4())
conn.execute("BEGIN IMMEDIATE")
conn.execute("INSERT INTO sessions (id, user_id, created_at, status) VALUES (?,?,?,?)",
(session_id, "user-2", now_iso(), "active"))
expired_id = str(uuid.uuid4())
conn.execute(
"INSERT INTO refresh_tokens (id, session_id, token_hash, created_at, expires_at, used_at) VALUES (?,?,?,?,?,?)",
(expired_id, session_id, hash_token("old"),
(datetime.now(timezone.utc) - timedelta(days=10)).isoformat(),
(datetime.now(timezone.utc) - timedelta(days=3)).isoformat(),
(datetime.now(timezone.utc) - timedelta(days=9)).isoformat()))
live_id = str(uuid.uuid4())
conn.execute(
"INSERT INTO refresh_tokens (id, session_id, token_hash, created_at, expires_at) VALUES (?,?,?,?,?)",
(live_id, session_id, hash_token("live"), now_iso(),
(datetime.now(timezone.utc) + timedelta(days=30)).isoformat()))
conn.commit()
before = conn.execute("SELECT COUNT(*) FROM refresh_tokens").fetchone()[0]
conn.execute("BEGIN IMMEDIATE")
conn.execute("DELETE FROM refresh_tokens WHERE expires_at < ?", (now_iso(),))
conn.commit()
after = conn.execute("SELECT COUNT(*) FROM refresh_tokens").fetchone()[0]
remaining_ids = [r[0] for r in conn.execute("SELECT id FROM refresh_tokens").fetchall()]
assert before == 2 and after == 1 and remaining_ids == [live_id]
print(f"[4] cleanup: {before} rows -> {after} row after purging expired tokens (live token {live_id[:8]}... kept)")
conn.close()
if __name__ == "__main__":
scenario_1_normal_rotation()
scenario_2_replay_detected()
scenario_3_concurrent_race()
scenario_4_cleanup()
print("\nALL SCENARIOS PASSED")
Running python3 s79_refresh_rotation.py (session and token identifiers are randomly generated UUIDs and will differ on every run; the counts, statuses, and outcome pattern shown are deterministic and asserted by the script itself) produced:
[1] normal rotation: OK (two sequential rotations succeeded, session stayed active)
[2] replay detected as expected: session 848f3c43-ec54-46c9-a3d2-54d4c6e6f461 marked compromised, all tokens revoked
session status=compromised, 2/2 tokens revoked
[3] concurrent race on the same still-valid token: outcomes = {'t1': ('rotated', 'c36c6e6c-22e5-4a09-ac8d-df596b213b6d'), 't2': ('replay', 'session c5ff49d4-a8ae-4a4e-95a1-924e24584ed6 marked compromised, all tokens revoked')}
session status after the race: compromised <- the false-positive compromise call-out in the answer
[4] cleanup: 2 rows -> 1 row after purging expired tokens (live token b5da7434... kept)
ALL SCENARIOS PASSED
Scenario 3 is the important one: two threads race to rotate the same still-valid token at the same instant. BEGIN IMMEDIATE serializes them at the database level, so exactly one succeeds (the assertion outcomes == ["replay", "rotated"] holds regardless of which thread happens to win the operating system's scheduling, since only the aggregate outcome, not which named thread gets which result, is guaranteed), and the loser's transaction, once unblocked, observes replaced_by already set and is correctly routed into the replay branch, marking the session compromised.
Trade-offs and pitfalls
- The genuine race in scenario 3 is also this design's known weakness. Two legitimate concurrent uses of the same still-valid token (a network retry firing a second request before the first one's response arrives, a common client bug, not an attack) produce exactly the same signature as an actual replay attack: the token chain cannot tell them apart, because both present the same
token_hasha second time. The mitigation is client-side, not server-side: refresh calls should be idempotent per attempt (a client-generated request id the server can deduplicate) so a genuine retry never reaches the server as a second distinct redemption. - Storing the raw refresh token instead of its hash. If
token_hashwere the literal token, a read-only database compromise (a leaked backup, a misconfigured replica) would hand out live, usable credentials. Hashing means a database leak alone is not a credential leak. - Deleting rows the instant they are used or expired. This destroys the forensic trail that lets you determine, after the fact, which token in a chain was replayed and when, which is often needed for incident response and user notification. Keep a short retention window past expiry/use before the cleanup job removes rows.
- Rotating without revoking the whole session on replay. A design that only revokes the individual replayed token, and not the rest of the chain, leaves an attacker who captured multiple tokens from the same session free to keep using the others. The session-level
compromisedstate is what actually closes the account, not the token-levelrevokedflag alone. - Skipping the transaction boundary "to keep it simple." Doing the read and the write as two separate statements without a surrounding lock reopens exactly the race scenario 3 exists to close: two concurrent requests can both read
replaced_by IS NULLbefore either has written, and both proceed to rotate, corrupting the chain.
Write Kotlin code for Android that implements thread-safe token-refresh logic using coroutines. Requirements: when multiple concurrent API calls receive a 401, only a single refresh request should run; other callers should suspend and resume with the new access token once refresh completes. Persist the new tokens atomically using EncryptedSharedPreferences or a KeyStore-wrapped key, and handle a failed refresh by triggering app logout.
Sample Answer
Direct answer
The core problem is coordination, not encryption: when several API calls hit a 401 at once, exactly one of them should trigger a network refresh, and every other caller should suspend and resume with that same result instead of each firing its own refresh (which would race the server's refresh-token rotation and could invalidate itself). The pattern is a mutex-guarded, shared in-flight Deferred<String?>: the first caller to see no refresh in progress starts one and publishes the Deferred under the lock; every other caller reads that same Deferred under the lock and then awaits it outside the lock, so waiting callers do not block each other, only the brief check-and-publish step is serialized.
Structured elaboration
Approach. A Mutex protects a single nullable field holding the in-flight refresh (refreshJob: Deferred<String?>?). getValidToken() first does a cheap, lock-free check: if the currently stored access token is not expired, return it immediately, since most calls should not need to touch the mutex at all. Only on an actual 401 (or a pre-emptive expiry check) does it take the lock to either read an already-running Deferred or start a new one. The refresh itself runs on a coroutine scope that is not owned by any single caller: if it were launched on the scope of whichever caller happened to trigger it (for example, a screen's own viewModelScope), navigating away from that screen while other callers are still waiting would cancel the refresh out from under them. Persistence is written in a single commit() call so a process death mid-refresh can never leave a new access token paired with a stale refresh token, or vice versa. A failed refresh clears storage and triggers logout exactly once, no matter how many callers were waiting on it.
Kotlin implementation.
import kotlinx.coroutines.*
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import android.content.SharedPreferences
class RefreshFailedException(cause: Throwable) : Exception(cause)
/**
* Coordinates concurrent token refreshes so that N callers hitting a 401 at
* once produce exactly one network call, with every caller resolving to the
* same result.
*
* [externalScope] must NOT be tied to any single caller's lifecycle (do not
* pass a screen's viewModelScope here): cancelling one caller must never
* cancel a refresh that other callers are still awaiting. A process-lifetime
* scope with a SupervisorJob is the right shape.
*/
class TokenRefreshCoordinator(
private val authApi: AuthApi,
private val tokenStore: SecureTokenStore,
private val onLogout: suspend () -> Unit,
private val externalScope: CoroutineScope,
) {
private val mutex = Mutex()
private var inFlight: Deferred<String?>? = null
suspend fun getValidAccessToken(): String? {
tokenStore.getAccessToken()?.let { current ->
if (!isExpired(current)) return current
}
val deferred = mutex.withLock {
inFlight ?: externalScope.async { doRefresh() }.also { inFlight = it }
}
val result = deferred.await()
// Only clear the slot if it still points at OUR deferred: a newer
// refresh may already have been started and published by the time
// this caller wakes up and reacquires the lock.
mutex.withLock {
if (inFlight === deferred) inFlight = null
}
return result
}
private suspend fun doRefresh(): String? {
val refreshToken = tokenStore.getRefreshToken() ?: return failAndLogout()
return try {
val response = authApi.refreshToken(refreshToken)
// Both keys land in ONE commit, or neither does: no window
// where an access token and refresh token from different
// generations can be read back together.
tokenStore.saveTokensAtomically(response.accessToken, response.refreshToken)
response.accessToken
} catch (e: Exception) {
failAndLogout()
}
}
private suspend fun failAndLogout(): String? {
tokenStore.clearTokens()
onLogout()
return null
}
private fun isExpired(accessToken: String): Boolean {
val expClaimSeconds = decodeJwtExpiryClaim(accessToken) ?: return true
val skewSeconds = 30L // treat a token as expired slightly early to avoid racing the server
return System.currentTimeMillis() / 1000 >= expClaimSeconds - skewSeconds
}
}
/** Wraps EncryptedSharedPreferences (AndroidX Security Crypto) so both
* tokens are written or read together, never independently. */
class SecureTokenStore(private val prefs: SharedPreferences) {
fun getAccessToken(): String? = prefs.getString(KEY_ACCESS, null)
fun getRefreshToken(): String? = prefs.getString(KEY_REFRESH, null)
fun saveTokensAtomically(access: String, refresh: String) {
prefs.edit()
.putString(KEY_ACCESS, access)
.putString(KEY_REFRESH, refresh)
.commit() // synchronous, single atomic write
}
fun clearTokens() {
prefs.edit().clear().commit()
}
companion object {
private const val KEY_ACCESS = "access_token"
private const val KEY_REFRESH = "refresh_token"
}
}
Key points
- The check-and-publish of
inFlightis the only section under the lock;await()happens outside it, so 500 waiting callers do not serialize against each other, only against the microseconds it takes to read or write one field. - Referential equality (
inFlight === deferred) on cleanup, not just "is it non-null," so a caller that wakes up late never clears a newer refresh that started after its own. externalScopeis a constructor dependency, not created fresh per refresh, specifically so its lifetime is not tied to any one caller's lifecycle.commit(), notapply(), on theEncryptedSharedPreferenceswrite, becauseapply()is asynchronous and would reintroduce exactly the kind of partial-write window this design is trying to close.
Complexity. Each getValidAccessToken() call is O(1) outside the mutex (a map read plus a JWT expiry decode) and O(1) under the mutex (one field read/write). Total network calls across N concurrent 401s during one expiry window is O(1) (exactly one), which is the entire point of the coordinator; without it, N callers would each fire a refresh, an O(N) request storm.
Edge cases
- All callers arrive before the refresh starts, one arrives after it completes. The late caller's cheap first check (
isExpired) now sees the freshly-persisted token and returns immediately without ever touching the mutex. - Refresh fails. Every waiting
Deferredresolves tonull(not an exception escaping to callers, sincedoRefreshcatches internally), storage is cleared once, andonLogout()fires exactly once regardless of how many callers were waiting. - A second expiry happens right after a successful refresh completes. Cleanup nulled
inFlightonce the first refresh'sDeferredcompleted, so the next caller correctly starts a brand-new refresh rather than reusing a finished one. - App process death mid-refresh. Either the
commit()happened (both new tokens present) or it did not (both old tokens still present); there is no observable in-between state to recover from.
Worked example
Kotlin cannot be compiled or executed in this environment (no JVM/Kotlin toolchain available), so the coordination algorithm above was verified by porting it exactly onto Python's asyncio primitives, which map directly onto the Kotlin ones used (Mutex to asyncio.Lock, a shared Deferred to a shared asyncio.Future, structured async/await to the same). This proves the algorithm's behavior under real concurrency; it does not compile-check the Kotlin syntax above, which was hand-verified against current kotlinx.coroutines and AndroidX Security Crypto API shapes instead.
import asyncio
import random
class FakeAuthApi:
"""Stands in for the network call. Counts invocations so the test can
assert exactly one refresh happens per storm, and can be told to fail."""
def __init__(self, should_fail: bool = False):
self.call_count = 0
self.should_fail = should_fail
async def refresh_token(self, old_refresh: str) -> str:
self.call_count += 1
await asyncio.sleep(0.05) # simulated network latency
if self.should_fail:
raise RuntimeError("refresh endpoint returned 401")
return f"new-access-{self.call_count}-{old_refresh}"
class EncryptedPrefsStub:
"""Stands in for EncryptedSharedPreferences / Keystore-backed storage."""
def __init__(self, access: str, refresh: str):
self._data = {"access": access, "refresh": refresh}
self.write_count = 0
def get(self, key: str) -> str:
return self._data[key]
def atomic_put_all(self, **kv) -> None:
# models `.edit().putString(...).commit()`: a single synchronous,
# all-or-nothing write
self._data.update(kv)
self.write_count += 1
def clear(self) -> None:
self._data.clear()
self.write_count += 1
class RefreshManager:
"""Direct analogue of the Kotlin TokenRefreshCoordinator above:
self._lock <-> Mutex, self._inflight <-> inFlight: Deferred<String?>?
"""
def __init__(self, api: FakeAuthApi, prefs: EncryptedPrefsStub, on_logout):
self._api = api
self._prefs = prefs
self._on_logout = on_logout
self._lock = asyncio.Lock()
self._inflight: asyncio.Future | None = None
def _is_expired(self, access: str) -> bool:
return access.startswith("expired")
async def get_valid_token(self) -> str | None:
current = self._prefs.get("access")
if not self._is_expired(current):
return current
async with self._lock:
if self._inflight is None:
self._inflight = asyncio.ensure_future(self._do_refresh())
future = self._inflight
try:
token = await future
finally:
async with self._lock:
if self._inflight is future and future.done():
self._inflight = None
return token
async def _do_refresh(self) -> str | None:
try:
new_access = await self._api.refresh_token(self._prefs.get("refresh"))
self._prefs.atomic_put_all(access=new_access, refresh=f"rot-{new_access}")
return new_access
except Exception:
self._prefs.clear()
self._on_logout()
return None
async def storm(n_callers: int, api: FakeAuthApi, prefs: EncryptedPrefsStub, on_logout, mgr: "RefreshManager | None" = None):
# Accept an existing manager to reuse. A freshly-constructed RefreshManager
# trivially starts with _inflight=None regardless of whether a PRIOR
# manager's cleanup logic actually works, so reusing the SAME instance
# across waves is what lets a later assertion depend on cleanup having
# genuinely happened, rather than on the fact that a new object starts empty.
if mgr is None:
mgr = RefreshManager(api, prefs, on_logout)
async def caller(i):
await asyncio.sleep(random.uniform(0, 0.01)) # jitter: real overlap, not lockstep
return await mgr.get_valid_token()
results = await asyncio.gather(*(caller(i) for i in range(n_callers)))
return mgr, results
async def scenario_success():
random.seed(1234) # pinned for reproducibility
api = FakeAuthApi(should_fail=False)
prefs = EncryptedPrefsStub(access="expired-old", refresh="refresh-abc")
logout_calls = []
mgr, results = await storm(25, api, prefs, lambda: logout_calls.append(1))
assert api.call_count == 1, f"expected exactly 1 network refresh for 25 concurrent 401s, got {api.call_count}"
assert all(r == results[0] for r in results), "all concurrent callers must resolve to the SAME new token"
assert results[0] is not None and results[0].startswith("new-access-1-")
assert logout_calls == []
assert prefs.write_count == 1, f"persistence must happen exactly once (atomic), got {prefs.write_count} writes"
print(f"[success] 25 concurrent 401s -> {api.call_count} network call, "
f"{prefs.write_count} atomic write, all 25 callers got token={results[0]!r}")
# Prove the cleanup path directly on the SAME manager instance, before
# starting a second wave: _inflight must already be back to None here
# BECAUSE the first refresh's completion nulled it out, not because this
# is a fresh object that never had anything in flight.
assert mgr._inflight is None, "cleanup should have nulled _inflight after the first refresh completed"
print(f"[success] confirmed on the SAME manager instance: mgr._inflight is None "
f"after wave 1's cleanup ran (id(mgr)={id(mgr)})")
prefs._data["access"] = "expired-again"
# Pass the SAME mgr into the second wave instead of letting storm() build
# a new RefreshManager - this is what makes the assertion below actually
# exercise the coordinator's own inflight-cleanup logic.
mgr2, results2 = await storm(10, api, prefs, lambda: logout_calls.append(1), mgr=mgr)
assert mgr2 is mgr, "second wave must reuse the exact same manager instance, not a fresh one"
assert api.call_count == 2, "a later expiry must trigger a NEW refresh, not reuse the completed future"
assert all(r == results2[0] for r in results2), "all second-wave callers must resolve to the SAME new token"
print(f"[success] second expiry wave on the SAME mgr (id={id(mgr2)}) -> "
f"network call count now {api.call_count}, new token={results2[0]!r}")
async def scenario_failure():
random.seed(99)
api = FakeAuthApi(should_fail=True)
prefs = EncryptedPrefsStub(access="expired-old", refresh="refresh-xyz")
logout_calls = []
mgr, results = await storm(15, api, prefs, lambda: logout_calls.append(1))
assert api.call_count == 1, f"one failed refresh attempt should still mean exactly 1 network call, got {api.call_count}"
assert all(r is None for r in results), "every caller must observe the failure as None, not hang or crash"
assert logout_calls == [1], f"on_logout must fire exactly once, fired {len(logout_calls)} times"
print(f"[failure] 15 concurrent 401s against a failing refresh -> {api.call_count} network call, "
f"logout fired {len(logout_calls)}x, all callers got None")
async def main():
await scenario_success()
await scenario_failure()
print("\nALL SCENARIOS PASSED")
if __name__ == "__main__":
asyncio.run(main())
Running this script (python3 s78_refresh_coordination.py) produces:
[success] 25 concurrent 401s -> 1 network call, 1 atomic write, all 25 callers got token='new-access-1-refresh-abc'
[success] confirmed on the SAME manager instance: mgr._inflight is None after wave 1's cleanup ran (id(mgr)=4397049776)
[success] second expiry wave on the SAME mgr (id=4397049776) -> network call count now 2, new token='new-access-2-rot-new-access-1-refresh-abc'
[failure] 15 concurrent 401s against a failing refresh -> 1 network call, logout fired 1x, all callers got None
ALL SCENARIOS PASSED
The second wave now reuses the identical mgr object from the first wave (same id() printed both times), not a freshly-constructed manager, so the mgr._inflight is None assertion right before it genuinely depends on wave 1's cleanup having run, not on starting from an empty object. This was checked against a negative control: temporarily breaking the cleanup line (self._inflight = None) inside get_valid_token()'s finally block makes this exact same test suite fail immediately, with AssertionError: cleanup should have nulled _inflight after the first refresh completed - confirming the test can actually catch the bug it claims to guard against, not just pass regardless of whether that logic works. This confirms, under actual concurrent execution rather than by inspection: 25 simultaneous callers collapse to exactly one network call and one atomic persistence write, and they all observe the identical resulting token; a second, later expiry on the SAME coordinator instance correctly triggers a fresh refresh instead of reusing the completed one, because its own cleanup logic genuinely nulled the in-flight slot; and a failing refresh under load still produces exactly one network call, resolves every waiting caller to None, and fires the logout callback exactly once, never once per waiter.
Trade-offs and pitfalls
- Scoping the refresh coroutine to a single caller's lifecycle. The most common real mistake in this pattern: launching the refresh on a screen's own scope means navigating away cancels it, and every other caller still awaiting that
Deferredreceives aCancellationExceptioneven though their own request context is still alive. The refresh must live on a scope no single caller owns. - Using
apply()instead ofcommit()for the token write.apply()queues the write asynchronously and returns immediately, which reopens the exact race this design exists to close: a caller could read the old refresh token from disk microseconds after the in-memory refresh completed but before the write actually lands. - Comparing
Deferredreferences with==instead of===. Kotlin data classes and some wrapper types can be structurally equal without being the same instance; using structural equality on the cleanup check can incorrectly null out a different, newer in-flight refresh. - Not treating the failure path as shared state too. It is tempting to only think about the success path when designing single-flight coordination; the failure path needs the same exactly-once guarantee (one logout call, one storage clear) or a refresh storm under a genuinely broken auth server turns into a logout storm instead.
Design a secure and user-friendly logout and token-revocation strategy for a mobile app. Cover client-side removal of credentials, server-side revocation of refresh tokens, handling multiple signed-in devices, push- or polling-based notification to other devices, and techniques to ensure tokens are unusable after logout even if an attacker had already extracted them.
Sample Answer
Direct answer
Logout has to succeed instantly from the user's point of view (clear local credentials the moment the button is tapped, regardless of network state) while also being backed by a server-side revocation that does not depend on that instant local clear alone, because an attacker who already extracted a copy of the token before logout would be unaffected by the device wiping its own copy. The design that closes both gaps is: clear locally first for responsive user experience (UX), revoke the refresh token server-side so the session cannot be extended past its current access token, and keep access tokens short-lived so even an already-stolen, not-yet-expired access token has a small, bounded window rather than an indefinite one.
Structured elaboration
Client-side removal of credentials. The moment logout is triggered, the app deletes the access and refresh tokens from platform-backed secure storage (iOS Keychain, Android Keystore-backed storage), clears any in-memory session state, and cancels background jobs that would otherwise silently refresh the session again. This happens unconditionally and immediately, without waiting for the server call in the next step to succeed, because a user who tapped "log out" should see a logged-out app even if they are offline at that moment.
Server-side revocation of refresh tokens. The device sends a revoke request identifying the specific refresh token (or its session) to the server, which marks the corresponding session row revoked in the authoritative store. From that point, no future refresh call for that session can produce a new access token: the server checks session status on every refresh, so the compromise is bounded going forward even though it does nothing about tokens issued before the revoke.
Handling multiple signed-in devices. Sessions are per-device, not per-user, so each device has its own session row, refresh token, and revocation status. This makes two distinct actions both first-class operations rather than one being a hack on top of the other:
- "Log out this device": revoke only the current session; other devices are untouched.
- "Log out everywhere": revoke every session row for the user in one transaction, which is the operation a user reaches for after realizing their account was compromised, and it needs to actually be atomic across all sessions, not a loop of independent per-device calls that could partially fail.
Push- or polling-based notification to other devices. Revoking a session server-side stops that device's next refresh from succeeding, but it does not by itself tell the device to stop acting on its still-valid, not-yet-expired access token, or update its UI to a logged-out state. Two complementary mechanisms close this gap:
- Push: the server sends a silent, data-only push (Apple Push Notification service, APNs, or Firebase Cloud Messaging, FCM) to the affected device's registered push token, instructing the app to clear local credentials and show the logged-out screen immediately, without waiting for the user to notice.
- Polling fallback: since push delivery is best-effort (a device can be offline, in airplane mode, or have background delivery throttled by the operating system), the app also checks session status on foreground and at a low-frequency background interval, so a device that missed the push still self-corrects the next time it is actually used.
Ensuring tokens are unusable after logout even if already extracted. This is the harder half of the question, because "the device deleted its copy" says nothing about a copy an attacker took earlier (malware, a debug log, a memory dump). Four techniques combine to close that gap:
- Short-lived access tokens. If access tokens live for minutes, a stolen access token is only useful for however many minutes remain on it, an upper bound that exists regardless of whether logout ever happens.
- Server-side refresh-token revocation, checked on every refresh. Even if the attacker has the refresh token too, revoking it server-side means their next refresh attempt is rejected, so they cannot extend the stolen access indefinitely.
- Storing only a hash of the refresh token server-side. If the token store itself is ever read (a backup leak, a compromised replica), what is exposed is not directly usable, mirroring password-hashing practice.
- An access-token denylist for the remaining lifetime of the current token, for high-sensitivity actions. Since a short-lived access token cannot itself be "revoked" the way a refresh token can (its validity is normally judged only by its own signature and expiry, with no per-request database lookup, which is what makes it fast), a denylist keyed by the token's unique identifier (
jti) and checked only on sensitive endpoints gives you the ability to immediately invalidate even an unexpired access token, at the cost of that one lookup, without giving up the no-lookup fast path for ordinary requests.
Worked example
A user logs into a note-taking app on their phone and a tablet, then loses the phone and reports it stolen from the tablet:
- Normal logout on the phone (before it was lost). User taps "log out." The app immediately clears the Keychain-stored tokens and shows the login screen. In parallel, it calls
POST /auth/logoutwith the phone's session id. The server marks that sessionrevokedand returns success; if this call had failed (no network), the phone would still show logged-out locally and would retry the server call on next connectivity. - The theft scenario. The phone is stolen while still logged in (never got to run step 1's local clear). From the tablet, the user opens "Manage devices," sees "iPhone, last active 2 hours ago," and taps "Log out this device."
- Server-side action. The server revokes the phone's session row and publishes a revocation event. Because access tokens for this app are short-lived, and because the phone's already-issued access token might still be technically unexpired for a few more minutes, the server also adds that token's
jtito the denylist so sensitive endpoints reject it immediately rather than waiting out its natural expiry. - Notification. The server sends a silent push to the phone's registered push token. If the thief has the phone online and connected, the app receives it, clears local credentials, and shows the logged-out screen without any user interaction on that device (the thief sees the app log itself out). If the phone is offline (airplane mode, powered off), nothing happens until it reconnects; at that point its next API call is rejected by the denylist check or, once the access token naturally expires, its next refresh attempt is rejected by the revoked session row.
- Bound on exposure. From the moment the tablet's "log out this device" action completes, the thief has, at most, however long it takes them to make one more API call before hitting either the denylist (if the endpoint checks it) or the natural access-token expiry (if it does not), never an indefinite window.
Trade-offs and pitfalls
- Treating "revoke the refresh token" as sufficient on its own. A revoked refresh token stops the session from being extended, but says nothing about an access token issued before the revoke that has not expired yet. This is the single most common gap: teams implement refresh-token revocation, verify it works on the next login attempt, and stop there, leaving a live window equal to the access-token's full remaining lifetime.
- Making the access-token denylist the default check on every request. Checking a denylist on every single API call reintroduces the per-request database lookup that short-lived, self-verifying access tokens were designed to avoid, at scale. Reserve it for sensitive endpoints (payments, account settings, data export) where the cost is worth the immediate-invalidation guarantee, and let ordinary reads rely on the token's short natural expiry instead.
- Blocking the local logout UI on the server call. If the app waits for
POST /auth/logoutto succeed before clearing local state, a network failure at exactly the wrong moment leaves the user looking logged-in when they are not, which is both a confusing user experience and, if they hand the device to someone else believing they logged out, a real security gap. Clear locally first, unconditionally, and reconcile the server call asynchronously. - "Log out everywhere" implemented as a loop of per-device revoke calls. If one call in the loop fails partway through, the user is left with a false sense of security, believing every device is logged out when one is not. This needs to be a single atomic operation against the session store, not a client-side or naive server-side loop.
- Relying on push as the actual security boundary rather than a UX improvement. As with any push-based notification, delivery is not guaranteed. The denylist and revoked-session checks are what actually make a device stop working; the push just makes it stop working sooner, when it arrives.
Explain how to implement certificate pinning on Android using Network Security Config, and propose a robust fallback strategy. Cover static pins in the config, using multiple pins including backups, considerations for captive portals and enterprise proxies, and how you would update pins in the field without requiring an immediate app update.
Sample Answer
Approach
Android's Network Security Config (NSC) implements certificate pinning declaratively: a static pin-set compiled into the app's resources at build time, referenced from the manifest via android:networkSecurityConfig. This is the right tool for a baseline, robust pin set that rarely changes. It is important to be precise about one thing NSC does NOT do: the pin-set element has no built-in mechanism to fetch an updated pin list from a server at runtime. It is read once, from the resource bundled in the installed Application Package (APK), and stays fixed until the app itself is updated. Genuinely field-updatable pinning, changing the trusted pins without shipping a new APK, requires a second, programmatic layer (a custom TrustManager, typically via a library like OkHttp's CertificatePinner) that fetches and verifies pins at runtime, with NSC's static pin-set serving as the fallback the app can always trust even if that dynamic layer is unreachable or compromised.
Static pins in the config
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">api.example.com</domain>
<!-- Primary pin (current leaf or intermediate SPKI hash) plus a backup
pin generated from a DIFFERENT key pair, so rotating to the backup
does not require an app update. -->
<pin-set expiration="2027-01-31">
<pin digest="SHA-256">AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</pin>
<pin digest="SHA-256">BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB=</pin>
</pin-set>
</domain-config>
<!-- Debug-only relaxation so a developer can proxy traffic through a local
debugger; never present in the production build. -->
<debug-overrides>
<trust-anchors>
<certificates src="system" />
<certificates src="user" />
</trust-anchors>
</debug-overrides>
</network-security-config>
Validated as well-formed Extensible Markup Language (XML) with Python's standard-library xml.dom.minidom parser; this confirms the document structure is correct, not that it is semantically accepted by Android specifically, which would require an actual Android build to check.
Key points
- Pin the Subject Public Key Info (SPKI) hash, not the whole certificate. Pinning the public key survives a certificate reissue against the same key pair, and is what the
pinelement'sdigest="SHA-256"attribute expresses above. - Always ship at least two pins: a primary and a backup, generated from different key pairs. If the primary key is ever replaced (planned rotation or an emergency), the backup pin, already present in every installed app, lets the app trust the new certificate immediately, with no app-store update required, as long as the new certificate matches the backup pin.
- Scope pins to the specific domain, and
includeSubdomainsonly when genuinely needed. A global pin-set with no domain scoping is a common Network Security Config mistake that turns a certificate problem on one subdomain into an outage for the whole app. debug-overridesnever ships to production. It exists so a developer can inspect traffic through a local proxy during development; it must be scoped out of release builds (Android's Gradle build system does this automatically when the block is placed under a debug-only resource path, which is the standard pattern).
Robust fallback strategy for captive portals and enterprise proxies
Neither of these should cause the app to silently disable pinning; both should be handled as an explicit, user-visible state, not a security downgrade:
- Captive portals (airport WiFi, hotel networks) intercept traffic before real internet access is granted, typically returning an HTTP redirect or a non-matching certificate for any request. Detect this using the OS's own connectivity APIs (Android's
ConnectivityManagerreports a captive-portal-blocked network state) rather than inferring it from a pinning failure, and when detected, show the user a clear "connect to this network's login page" flow (opened outside the pinned app traffic, in the system browser) instead of silently retrying without pinning. - Enterprise Man-in-the-Middle (MITM) proxies, where an organization's device management installs its own root certificate to inspect traffic, are a policy decision made by the device owner (often the user's employer), not something a public-facing app should accommodate by weakening its own pinning. The correct response to a pinning failure caused by a corporate proxy is a clear in-app message explaining that the network is intercepting secure traffic and the app cannot verify the connection is safe, not a silent fallback to trusting the proxy's certificate.
Updating pins in the field without an immediate app update
Since NSC's pin-set cannot fetch updates at runtime, achieving this requires layering a programmatic pinning mechanism (a custom TrustManager, most commonly implemented via OkHttp's CertificatePinner API) alongside NSC rather than relying on NSC alone:
- The app ships with NSC's static pin-set as in the config above; this is the backstop that always works, even if the app has never been able to reach the network for a dynamic update.
- Separately, the app's networking layer (OkHttp or equivalent) is configured with a
CertificatePinnerbuilt from a pin list the app fetches from a signed manifest endpoint at startup (and periodically thereafter), verifying the manifest's signature against a fixed, immutable verification key baked into the app before trusting any pin it contains. - Both layers are checked; a connection is trusted only if it satisfies whichever layer is currently authoritative for that pin set, and the app treats a manifest-fetch failure as "use the last successfully verified dynamic pin set, falling back to the static NSC pin-set" rather than as a reason to disable pinning altogether.
This two-layer design, a static NSC backstop plus a separately verified, signed pin manifest carrying its own TTL, expiry semantics, and an emergency-rollback path for a compromised signing key, is what actually delivers "update pins without an app update"; NSC alone cannot.
Complexity
This is a configuration and protocol-design problem, not an algorithmic one, so "complexity" here means operational cost rather than Big-O: validating a request against the static NSC pin-set is a fixed, small number of hash comparisons per TLS handshake (bounded by the number of pins in the set, typically two to four); the dynamic layer adds one manifest fetch at startup (and on a periodic timer), which is a single network round trip regardless of how many domains or pins the manifest covers, plus a constant-time signature verification over that manifest.
Edge cases
- Certificate rotation without a matching backup pin already deployed. If the primary key changes and no already-installed backup pin matches the new certificate, every installed app with pinning enforced loses connectivity until updated; this is why the backup pin must be generated and distributed BEFORE the primary key is rotated, not after.
- Manifest fetch succeeds but the signature verification fails (a corrupted response, a compromised distribution channel). The app must treat this as "no update available," never as "trust the unverified pins anyway."
- Clock skew on the device affecting the
pin-set expirationdate or the dynamic manifest's validity window; allow a small, explicit tolerance rather than failing pinning entirely over a few minutes of drift. - Captive portal false negative: a network that behaves like a captive portal but isn't reported as one by the OS API; the app should still fail closed (block the pinned connection, show the explanatory message) rather than silently disabling pinning as a catch-all fallback.
Explain mobile app signing and code-signing key management on Android and iOS. Cover the differences between APK/AAB signing, Play App Signing, keystore files, and iOS provisioning profiles and distribution certificates, and explain why protecting signing keys is critical for update integrity and for preventing a malicious app update from reaching users.
Sample Answer
Direct answer
Code signing is how an operating system and an app store answer one question before installing or updating an app: did this binary really come from the developer who published the last one? Android and iOS solve it with different mechanics (a developer-held keystore versus store-managed certificates and profiles), but the property they protect is the same: an attacker who does not hold the signing key cannot push a binary that the device or the store will accept as a legitimate update.
Structured elaboration
Android: APK/AAB signing and Play App Signing. Android builds are shipped as an Android Package (APK) or, for Play Store submissions, an Android App Bundle (AAB), and both are signed with a developer's private signing key held in a keystore file. The signature is what the platform checks on install and, critically, on every subsequent update: Android refuses to install an update unless it is signed with the same key (or key lineage) as the version already on the device. Google's Play App Signing changes where that final signing key lives: instead of the developer holding the one key that ever touches a user's device, the developer signs their AAB upload with an upload key, Google verifies that upload and re-signs the final APK with an app signing key that Google manages and can help recover if lost. This does not remove the developer's responsibility to protect the upload key, it adds a second, Google-managed layer of protection around the key that actually reaches users.
iOS: provisioning profiles and distribution certificates. iOS uses a different pairing: a distribution certificate, which is a public/private key pair issued by Apple that proves your developer identity and signs the binary, and a provisioning profile, which bundles that certificate identity with an app ID, entitlements, and (for non-App-Store distribution) a device list, and is what actually authorizes the signed binary to run on a given class of device. App Store builds are re-signed by Apple after review using Apple's own distribution mechanism, but the developer's distribution certificate is still what establishes that the uploaded binary came from the registered developer account in the first place.
Keystore files as the trust anchor. On Android, the keystore file (historically a .jks, now more commonly a .keystore in PKCS12 format) holds the actual private key material. It is the single artifact that determines "can this build be accepted as an update to the app already on users' devices." There is no password-reset flow for a lost Android upload key outside of Play App Signing's recovery path; losing it without that safety net means the developer can never again ship an update to the existing app listing under the original signature.
Why protecting the signing key matters for update integrity. The signature is the entire trust mechanism for the update channel. If an attacker obtains the signing key (through a compromised build server, a leaked keystore file in a public repository, or a stolen developer laptop), they can build and distribute a malicious binary that both the operating system and, for side-loaded Android installs, the user's own device will accept as a legitimate update from the real developer, no additional social engineering required beyond getting the victim to install it. This is categorically worse than a single compromised server, because it lets the attacker impersonate the developer's entire update history going forward, and revoking the key does not retroactively undo installs that already happened.
Worked example
A team stores its Android release keystore file and its password directly in the continuous integration (CI) pipeline's public repository configuration, "temporarily," to unblock a release. Six months later a security researcher finds the exposed keystore in the repository's commit history (removing a file from the latest commit does not remove it from git history). Because Android trusts any binary signed with the matching key as a legitimate update, an attacker holding that keystore could build a version of the app with additional permissions or a data-exfiltrating payload and distribute it as a side-loaded "update," and any user who installs it over the existing app would have their real app silently replaced, no store review involved. The fix is not just rotating the leaked key: since revoking access does not invalidate binaries already signed with the old key, the team also needs Play App Signing's key upgrade path (which lets Google re-sign future updates with a new app signing key while phasing out the compromised one) and, if that is not in place, to warn users through an in-app or external channel that any update not delivered via the Play Store should be treated as suspicious until the migration completes.
Trade-offs and pitfalls
Losing the Android upload key without Play App Signing enrolled is effectively unrecoverable: without a shared key lineage, there is no way to publish an update to the existing listing, and the standard remedy is publishing under a new package name, which forfeits the app's install base, reviews, and store ranking history.
Committing a keystore file, .p12, or provisioning profile into source control, even a private repository, is a common mistake: private repositories still have contributors, CI logs, and backup exposure, and the history persists even after the file is later removed. Keys belong in a secrets manager or the CI platform's encrypted secret storage, referenced at build time, never committed.
Sharing one signing identity across every environment (development, staging, production) means a compromise or leak in a lower-trust environment (a contractor's laptop, a staging CI runner) has production-update-channel consequences. Separate signing identities per distribution channel, with the production key held by the fewest possible people and, ideally, in a hardware-backed store, limit blast radius.
Provisioning profile expiry is an operational trap distinct from the security question: profiles and certificates have fixed expiration dates, and letting one lapse breaks the ability to build or distribute a new release until it is renewed. It is not a security compromise, but teams that treat signing infrastructure as "set once and forget" get caught by it at the worst time, typically right before a release deadline.
Unlock Full Question Bank
Get access to all 30 Secure Coding and Application Security interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.