Secure S3 Upload Patterns and TypeScript Structural Typing
System DesignModel answerLast updated
Architect secure, direct S3 uploads via pre-signed URLs/IAM and analyze TypeScript structural typing alongside React useEffect async cleanup.
This technical screen assesses two core software engineering domain areas: cloud security architecture on AWS and frontend engineering using React with TypeScript.
Section A: Cloud Storage & Security Architecture
Your web application needs to allow users to upload files directly from their browsers into an Amazon S3 bucket.
- Architecture & Flow: Design a secure, direct-to-S3 upload process. Explain how to achieve this without embedding long-lived AWS credentials in the frontend and without making the target S3 bucket publicly accessible.
- IAM Configuration: Detail the exact IAM policy principles and permissions you must grant to your backend server to enable this pattern safely.
- Data Integrity & Enforcement: Explain how to restrict key names, payload sizes, and media types so that malicious actors cannot upload unauthorized data or overwrite existing files.
Section B: Type Systems & React State Lifecycle
Examine the following TypeScript and React code snippet:
interface UserProfile {
id: string;
email: string;
isAdmin: boolean;
}
function UserCard({ user }: { user: UserProfile }) {
// Note: assume standard JSX rendering
return <div>{user.email}</div>;
}
- Structural vs. Nominal Typing: Contrast TypeScript's structural type system with nominal type systems found in languages such as Java or C#. How does structural typing affect what arguments can be validly passed into
UserCard? Explain the concept of excess property checking. - Asynchronous Effects & Memory Management: When fetching data inside a React
useEffecthook to populate a component likeUserCard, what bugs or edge cases (e.g., race conditions, unmounted state updates) can occur? Provide a code sample showing how to correctly handle component unmounting and fetch cancellation.
Hints
Hint 1
Consider AWS pre-signed URLs or pre-signed POST policies to delegate short-lived upload authority.
Hint 2
Ensure the application server uses temporary role-based credentials (STS) through IAM roles for compute instances rather than hardcoded access keys.
Hint 3
Think about how TypeScript checks types on direct object literals versus assigned variables (excess property checking).
Hint 4
Use AbortController inside the React useEffect cleanup function to prevent race conditions and unmounted state updates.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Section A: Direct S3 Upload Architecture & AWS IAM
1. Upload Architecture (Pre-signed URLs / Policies)
To keep the S3 bucket completely private while enabling high-throughput direct uploads from the client browser, use S3 Pre-signed URLs (or S3 Pre-signed POST policies).
End-to-End Execution Flow:
- Upload Request: The browser sends an authenticated API request to the backend server (e.g.,
POST /api/v1/uploads/request) containing metadata such as file name, file size (in bytes), and MIME type. - Validation & Pre-signing: The backend verifies user identity and authorization, enforces quota/file constraints, and generates an S3 key (e.g.,
uploads/user_9876/file_uuid4.png). Using the AWS SDK, the backend constructs a short-lived pre-signed POST policy or pre-signed PUT URL bound to that specific key. - Client Upload: The backend returns the signed URL/policy fields to the browser. The browser performs a direct
PUTorPOSTHTTP request containing raw file bytes to Amazon S3. - Processing / Notification: S3 validates the request signature. Upon success, S3 triggers an asynchronous notification event (via Amazon EventBridge, SQS, or S3 Event Notifications to AWS Lambda) to notify the backend that the object has landed.
+---------+ 1. POST /api/v1/uploads/request +----------------+
| | ----------------------------------------------> | |
| | <---------------------------------------------- | |
| Client | 2. Pre-Signed POST Policy / URL | Application |
| Browser | | Backend Server |
| | 3. Direct HTTP PUT/POST File Data | (IAM Role) |
| | ----------------------------------------------\ +----------------+
+---------+ |
| |
v v
+----------------------------------------------------------------------------+
| Amazon S3 Bucket |
| (Private Access / Block Public Access On) |
+----------------------------------------------------------------------------+
S3 Bucket Security Configuration:
- Block Public Access: All 4 S3 Block Public Access settings remain enabled.
- Access Control: No bucket ACLs are granted (
BucketOwnerEnforced). - CORS Configuration: Configure Cross-Origin Resource Sharing on the bucket to allow only your application origin to issue
PUTandPOSTmethods:[ { "AllowedHeaders": ["*"], "AllowedMethods": ["PUT", "POST"], "AllowedOrigins": ["https://app.yourdomain.com"], "ExposeHeaders": ["ETag"] } ]
2. Backend IAM Configuration
The backend application server should never hold long-lived static AWS access keys. It must inherit temporary credentials via an IAM Role attached to its compute resource (EC2 Instance Profile, ECS Task Role, EKS Pod Identity, or Lambda Execution Role).
Least-Privilege IAM Policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowScopedS3Uploads",
"Effect": "Allow",
"Action": [
"s3:PutObject"
],
"Resource": "arn:aws:s3:::app-storage-bucket/uploads/*"
},
{
"Sid": "AllowKMSKeyUsage",
"Effect": "Allow",
"Action": [
"kms:GenerateDataKey",
"kms:Decrypt"
],
"Resource": "arn:aws:kms:us-east-1:123456789012:key/c4a6b2e1-89ab-4c3d-bc12-9876543210fe"
}
]
}
Note: Include kms:GenerateDataKey if server-side encryption with AWS KMS keys (SSE-KMS) is enforced on the bucket. Enforce TLS transport via a bucket policy condition using aws:SecureTransport: false.
3. File Enforcements and Safeguards
To prevent overwrites and invalid payloads:
- Server-Generated Keys: The backend must independently generate the target S3 key (e.g., combining a server-validated user ID with a
UUIDv4). Never accept key names supplied directly by the client to prevent path traversal or overwriting existing objects. - Pre-signed POST Conditions: Prefer
generate_presigned_postover pre-signedPUTURLs because POST policies enforce conditions signed cryptographically:- Enforce exact content types:
["eq", "$Content-Type", "image/png"] - Enforce size boundaries:
["content-length-range", 1, 10485760](e.g., 1 Byte to 10 MB).
- Enforce exact content types:
# Python / boto3 Example
import uuid
import boto3
s3_client = boto3.client('s3')
def generate_secure_upload(user_id: str, content_type: str) -> dict:
allowed_types = {"image/png", "image/jpeg", "application/pdf"}
if content_type not in allowed_types:
raise ValueError("Unsupported media type")
unique_key = f"uploads/{user_id}/{uuid.uuid4()}"
response = s3_client.generate_presigned_post(
Bucket="app-storage-bucket",
Key=unique_key,
Fields={"Content-Type": content_type},
Conditions=[
{"Content-Type": content_type},
["content-length-range", 1, 10 * 1024 * 1024] # 10 MB Max
],
ExpiresIn=300 # Expires in 5 minutes
)
return response
Section B: TypeScript Structural Typing & React Async Effects
1. Structural Typing vs. Nominal Typing
Core Differences:
- Nominal Typing (Java, C#): Compatibility is strictly determined by explicit type names and inheritance hierarchies. An object is an instance of class
UserProfileonly if explicitly declared as such or extending it. - Structural Typing (TypeScript): Compatibility is determined solely by the shape and structure of the object interface. If an object possesses all the required properties defined in
UserProfile(id: string,email: string,isAdmin: boolean) with compatible types, TypeScript considers it compatible regardless of its declared type or constructor.
Impact on UserCard:
You can pass any generic object, API response object, or mock instance into UserCard without wrapping or casting it into a named class instance:
const apiData = {
id: "usr_100",
email: "[email protected]",
isAdmin: true,
createdAt: "2024-01-01"
};
// Valid: Extra properties ('createdAt') are allowed when passing assigned objects
<UserCard user={apiData} />
Excess Property Checking Exception:
When passing an object literal directly inline, TypeScript applies Excess Property Checking to protect against accidental typo mistakes or unused parameters:
// TS Error: Object literal may only specify known properties, and 'createdAt' does not exist in type 'UserProfile'.
<UserCard user={{
id: "usr_100",
email: "[email protected]",
isAdmin: true,
createdAt: "2024-01-01"
}} />
2. useEffect Pitfalls and Safe Async Pattern
Common Pitfalls:
- Race Conditions: If
userIdchanges rapidly (e.g., switching views from User A to User B), the network request for User A may resolve after the request for User B. This leaves the component rendering out-of-date or incorrect state for User A. - State Updates on Unmounted Components: In older React versions, calling
setStateafter a component unmounts triggered a console warning. Although React 18+ removed this specific warning, unhandled promises can still cause memory leaks by retaining closed-over variables. - Stale Closures & Double Effects: React 18
StrictModein development mounts, unmounts, and remounts components to stress-test missing cleanup logic.
Recommended Solution (AbortController Pattern):
To resolve network races and unmounted state updates, use the native AbortController interface inside the effect cleanup function:
import React, { useState, useEffect } from 'react';
interface UserProfile {
id: string;
email: string;
isAdmin: boolean;
}
interface UserCardProps {
userId: string;
}
export function UserCardContainer({ userId }: UserCardProps) {
const [user, setUser] = useState<UserProfile | null>(null);
const [isLoading, setIsLoading] = useState<boolean>(true);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Instantiate AbortController for this effect run
const controller = new AbortController();
const { signal } = controller;
async function fetchUserData() {
setIsLoading(true);
setError(null);
try {
const response = await fetch(`/api/v1/users/${userId}`, { signal });
if (!response.ok) {
throw new Error(`HTTP error status: ${response.status}`);
}
const data: UserProfile = await response.json();
setUser(data);
} catch (err: unknown) {
// Ignore abort errors caused by cleanup
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
setError(err instanceof Error ? err.message : 'An unknown error occurred');
} finally {
// Only turn off loading if request wasn't aborted
if (!signal.aborted) {
setIsLoading(false);
}
}
}
fetchUserData();
// Cleanup: abort ongoing fetch when component unmounts or userId changes
return () => {
controller.abort();
};
}, [userId]);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error}</div>;
if (!user) return <div>No user found</div>;
return (
<div>
<p>Email: {user.email}</p>
<p>Role: {user.isAdmin ? 'Admin' : 'Standard User'}</p>
</div>
);
}