Relevant source files
The following files were used as context for generating this wiki page:
This document outlines the execution flow that occurs when a user initiates the download of an automation evidence PDF from the TaskIntegrationChecks component. The primary goal of this process is to securely fetch a PDF document from the backend API, ensuring that the request is authenticated with a valid JSON Web Token (JWT).
The flow begins with a user interaction in the UI, leading to a series of function calls that prepare the download request. A critical part of this preparation involves obtaining a current and unexpired JWT. If the existing token is missing or nearing expiration, a refresh mechanism is triggered to acquire a new token from the authentication service. The trace concludes with the decoding of this JWT to extract its payload, primarily for managing its expiry and storage. This robust authentication mechanism ensures that only authorized users can access and download sensitive evidence documents.
Initiate Automation PDF Download
The process begins within the
TaskIntegrationChecksReact component, which is responsible for displaying and managing automated checks for a specific task. When a user clicks the "Download evidence PDF" button associated with a particular automation check, anonClickevent handler is triggered. This handler invokes thedownloadAutomationPDFfunction, passing along necessary identifiers such as thetaskId,automationId(which corresponds to thecheck.checkId),automationName(check.checkName), andorganizationId. This action signals the start of the evidence download sequence.Sources: apps/app/src/app/(app)/[orgId]/tasks/[taskId]/components/TaskIntegrationChecks.tsx:392-404
Prepare Download Request
The
downloadAutomationPDFfunction, located inapps/app/src/lib/evidence-download.ts, is responsible for constructing the specific API endpoint URL for the automation evidence PDF. It takes thetaskId,automationId,automationName, andorganizationIdas input. After forming the complete URL, it delegates the actual file fetching and download process to a genericdownloadFileutility function, along with fallback naming conventions for the downloaded file.Execute File Download with Authentication
The
downloadFilefunction inapps/app/src/lib/evidence-download.tshandles the core logic for downloading a file from a given URL. Before making thefetchrequest, it constructs the necessary HTTP headers. Crucially, it adds anX-Organization-Idheader and anAuthorizationheader. To obtain the value for theAuthorizationheader, it callsjwtManager.getValidToken(). This ensures that the download request is properly authenticated with a valid JWT. IfgetValidTokenthrows an error (e.g., authentication failed), the download process is aborted, and an error is thrown. Upon successful retrieval of the token, it proceeds to make thefetchrequest, processes the response, extracts the filename from theContent-Dispositionheader (or uses a fallback), and then initiates the browser-based file download.Retrieve or Refresh JWT
The
getValidTokenmethod of thejwtManager(a singleton instance ofJWTManagerfromapps/app/src/utils/jwt-manager.ts) is invoked to provide an up-to-date JWT. This method first attempts to retrieve a token and its expiry information fromlocalStorage. It then checks if the stored token is still valid or if it's expiring soon (within aREFRESH_THRESHOLDof 5 minutes).Token Validation LogicIf no token is found, or if the stored token is deemed to be expiring soon,
getValidTokenproceeds to callrefreshToken()to acquire a fresh token. Otherwise, it returns the existing, valid token directly. This proactive refresh mechanism minimizes the chances of an API request failing due to an expired token.Manage Token Refresh
The
refreshTokenmethod orchestrates the process of obtaining a new JWT. It includes important safeguards:- Concurrent Refresh Prevention: If a token refresh is already in progress (indicated by
this.refreshPromise), it waits for that existing refresh to complete instead of initiating a new one. - Cooldown Period: It enforces a
REFRESH_COOLDOWN(2 seconds) between refresh attempts to prevent excessive API calls. If an attempt is made too soon after the last, it will wait. After these checks, it setsthis.refreshPromiseto the result of_doRefreshToken()and awaits its completion. This ensures that only one refresh operation is active at any given time.
- Concurrent Refresh Prevention: If a token refresh is already in progress (indicated by
Perform Actual Token Refresh
The private
_doRefreshTokenmethod is where the actual fetching of a new JWT occurs. It attempts to acquire a new token through two primary mechanisms:- Session API: It first tries to get the JWT from the
authClient.getSession()call, which might set aset-auth-jwtheader in the response. - Token Endpoint: If the session API doesn't provide a new token, it then makes a
fetchrequest to the/api/auth/tokenendpoint. If a new token is successfully obtained from either method, it callsstoreToken()to persist the new token and its expiry, andscheduleRefresh()to set up the next automatic refresh.
- Session API: It first tries to get the JWT from the
Store New Token
Once a new JWT is acquired, the
storeTokenmethod is called. Its purpose is to securely store the token and its associated expiry information inlocalStorage. To determine the expiry time, it first callsdecodeJWTPayload()to parse the token and extract theexp(expiration) claim. Theexpvalue, which is a Unix timestamp in seconds, is converted to milliseconds and stored alongside the token itself. This ensures thatgetValidTokencan efficiently check the token's validity without re-decoding it every time.Decode JWT Payload
The final step in this trace is the
decodeJWTPayloadmethod. This utility function is responsible for parsing the JWT string to extract its payload. It performs a client-side, unverified decoding by splitting the token into its three parts (header, payload, signature), base64-decoding the payload part, and then parsing the resulting string as JSON. This decoded payload contains claims such as the token's expiration time (exp), which is crucial for thestoreTokenmethod to manage token lifecycle.
Key Observations
- Cross-module Boundaries: This flow demonstrates significant interaction across different modules:
TaskIntegrationChecks.tsx(React UI component) initiates the action.evidence-download.ts(utility for file downloads) handles the API request construction and execution.jwt-manager.ts(authentication utility) manages the JWT lifecycle.- The browser's
localStorageis used for persistent token storage. - External API endpoints (
/v1/tasks/.../pdffor download,/api/auth/tokenfor token refresh) are crucial for backend communication.
- Potential Failure Points and Handling:
- Network Errors:
fetchcalls indownloadFileand_doRefreshTokencan fail due to network issues. These are caught and result in error messages (e.g.,toast.errorinTaskIntegrationChecks,console.errorindownloadFileandjwt-manager). - Expired/Invalid JWT: The
jwtManageris specifically designed to handle this by proactively refreshing tokens before they expire and by attempting to refresh if an API call indicates an invalid token. If refresh fails,downloadFilewill throw an "Authentication failed" error. - Concurrent Refreshes: The
refreshTokenmethod prevents multiple simultaneous token refresh requests, which could lead to race conditions or unnecessary load on the authentication service. - Cooldown Period: A cooldown is enforced between refresh attempts to avoid hammering the server if refreshes repeatedly fail.
- Invalid JWT Format:
decodeJWTPayloadincludes atry-catchblock to handle malformed JWTs, preventing the application from crashing.
- Network Errors:
- Performance Considerations:
- Client-side Token Management: Storing and managing JWTs in
localStorageand performing client-side expiry checks (isTokenExpiringSoon) reduces the need for frequent server-side validation, improving responsiveness. - Proactive Refresh: Refreshing tokens before they expire minimizes delays in authenticated API calls.
- Optimized Refresh Logic: The
refreshTokenmethod's handling of concurrent requests and cooldowns prevents performance degradation due to excessive authentication attempts. - Asynchronous Operations: All network requests and token management operations are asynchronous, ensuring the UI remains responsive during these background tasks.
- Client-side Token Management: Storing and managing JWTs in
Sources: apps/app/src/app/(app)/[orgId]/tasks/[taskId]/components/TaskIntegrationChecks.tsx:392-404 apps/app/src/lib/evidence-download.ts:64-106 apps/app/src/utils/jwt-manager.ts:16-152