// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import * as s3 from 'aws-cdk-lib/aws-s3'; import * as ec2 from 'aws-cdk-lib/aws-ec2'; import * as kms from 'aws-cdk-lib/aws-kms'; import { Annotations, Duration, RemovalPolicy } from 'aws-cdk-lib'; import { RetentionDays } from 'aws-cdk-lib/aws-logs'; import { BuildingBlockScope, synthGuard } from '@aws-blocks/core/cdk'; import { resolveKmsEncryption } from '@aws-blocks/core/cdk/internal'; import type { ScopeParent } from '@aws-blocks/core'; import type { FileBucketOptions, CorsRule, ExternalBucketRef, ExternalKmsKeyRef } from './types.js'; import { deriveBucketName, validateBucketName } from './bucket-name.js'; import { DEFAULT_NONCURRENT_VERSION_EXPIRATION_DAYS, validateFileBucketOptions } from './validation.js'; import { BB_NAME } from './version.js'; export { FileBucketErrors } from './errors.js'; export type { FileBucketOptions, PutOptions, GetUrlOptions, PutUrlOptions, ScanOptions, FileContent, FileInfo, CorsRule, LifecycleRule, ExternalBucketRef, ExternalKmsKeyRef, ObjectLockOptions, FileDownloadClient, FileUploadClient, FileVersionInfo, FileDownloadDescriptor, FileUploadDescriptor, VersionedGetOptions, VersionedDeleteOptions, VersionedGetUrlOptions, GetOptionsFor, DeleteOptionsFor, GetUrlOptionsFor, } from './types.js'; /** Annotation-ID prefix for this block's synth warnings (matches the sibling storage blocks). */ const WARNING_PREFIX = '@aws-blocks/bb-file-bucket'; const httpMethodMap: Record = { GET: s3.HttpMethods.GET, PUT: s3.HttpMethods.PUT, POST: s3.HttpMethods.POST, DELETE: s3.HttpMethods.DELETE, HEAD: s3.HttpMethods.HEAD, }; export class FileBucket extends BuildingBlockScope { private bucket: s3.IBucket; /** * Reference an existing S3 bucket instead of provisioning a new one. * Mirrors the same factory exposed by the runtime build so the same code * works in both contexts. */ static fromExisting(bucketName: string): ExternalBucketRef { return { __brand: 'ExternalBucketRef' as const, bucketName }; } /** * Reference an existing customer-managed KMS key by ARN, to pass as the * `encryption` option so several buckets (or tables) can share one key. * Mirrors the same factory exposed by the runtime build so the same code * works in both contexts. */ static fromKmsKey(keyArn: string): ExternalKmsKeyRef { return { __brand: 'ExternalKmsKeyRef' as const, keyArn }; } constructor(scope: ScopeParent, id: string, options?: O) { super(id, { parent: scope, bbName: BB_NAME, vpc: { gatewayEndpoints: [ec2.GatewayVpcEndpointAwsService.S3] } }); if (options?.bucket) { // `fromExisting`: don't provision; bind to the pre-existing bucket and // grant read/write to the Blocks runtime Lambda. The wrapped bucket owns // its own encryption and Object Lock, so say so when either was set. const ignored = (['encryption', 'objectLock'] as const).filter(k => options[k] !== undefined); if (ignored.length > 0) { Annotations.of(this).addWarningV2( `${WARNING_PREFIX}:OptionsIgnoredForExisting`, `${ignored.join(', ')} ${ignored.length > 1 ? 'are' : 'is'} ignored for a bucket wrapped with FileBucket.fromExisting — ` + `configure ${ignored.length > 1 ? 'them' : 'it'} on the existing bucket itself.`, ); } this.bucket = s3.Bucket.fromBucketName(this, 'bucket', options.bucket.bucketName); this.bucket.grantReadWrite(this.executionRole); return; } // Resolve durability from the per-block option (a `'destroy'|'retain'` // string, normalized to a CDK RemovalPolicy) falling back to the // stack-wide `defaults`. This replaces the old `sandboxMode` context // read — the sandbox posture now flows in through the chosen preset, // exactly like bb-kv-store. Explicit `removalPolicy` from the customer // still takes precedence. `autoDeleteObjects: true` is only valid paired // with DESTROY (CDK validates this at construct time), so we derive the // two from the same resolved policy. const removalPolicy = options?.removalPolicy === 'destroy' ? RemovalPolicy.DESTROY : options?.removalPolicy === 'retain' ? RemovalPolicy.RETAIN : this.defaults.removalPolicy; const destroy = removalPolicy === RemovalPolicy.DESTROY; // Bucket name is derived from the scope chain: `fullId` unchanged when it // fits S3's 63 characters, else deterministically shortened (prefix + hash) // — the AWS-runtime and mock layers derive the same name independently. // Validate against S3's naming rules at synth so an invalid name fails // here rather than at `cdk deploy` (where CloudFormation rejects it with a // cryptic error). Run this first: an unusable bucket name is the most // fundamental synth error, so surface it before the option-level guards below. const bucketName = deriveBucketName(this.fullId); validateBucketName(bucketName); // Reject unsafe CORS and malformed noncurrent-version expiration at synth, // before `cdk deploy`. Shared with the local mock via validation.ts so both // paths reject exactly the same option combinations (mock↔CDK parity). validateFileBucketOptions(this.fullId, options); // Object Lock can't coexist with a DESTROY bucket: locked versions can't // be emptied (the auto-delete handler would fail on them), so the stack // teardown would fail. This depends on the resolved removal policy, a // CDK-only concept, so it lives here rather than in the shared validator. if (options?.objectLock && destroy) { throw new Error( `FileBucket "${this.fullId}": objectLock can't be combined with a 'destroy' removal policy ` + `(locked objects can't be deleted, so the stack teardown would fail). ` + `Pass removalPolicy: 'retain' on this FileBucket — required in a sandbox, whose preset destroys buckets by default.`, ); } // Encryption at rest: SSE-S3 by default; SSE-KMS with a dedicated or an // imported CMK on request. The `encryption` values (and the warning on an // unrecognized one) are shared with the DynamoDB-backed blocks. const encryptionChoice = resolveKmsEncryption(this, options?.encryption, { warningPrefix: WARNING_PREFIX, fromKmsKeyHint: 'FileBucket.fromKmsKey', }); // `'customer-managed'` mints a dedicated key here (rather than letting // `s3.Bucket` create one) so rotation is always on and the key shares the // bucket's removal policy: a DESTROY bucket doesn't orphan a billed, // rotating key, and a RETAIN bucket never outlives its key. const encryptionKey: kms.IKey | undefined = encryptionChoice.kind === 'imported' ? encryptionChoice.key : encryptionChoice.kind === 'customer-managed' ? new kms.Key(this, 'key', { description: `FileBucket ${this.fullId} encryption key`, enableKeyRotation: true, removalPolicy, }) : undefined; // Versioning stays on by default (secure default): a posture-driven // `versioned` default would require a new `BlocksDefaults` field in // core, which is out of scope for this change, so we keep the // default-on and bound its cost with a noncurrent-version expiration // below. const versioned = options?.versioned ?? true; // Opt-in server access logging: provision a dedicated, locked-down log // bucket and expire its logs after the framework retention. Kept // separate from the data bucket so log delivery can't loop back on it. // Resolves from the stack `defaults.storageAccessLogging` (then the // shared `defaults.accessLogging`) when no per-block option is given, so // a stack opts every FileBucket in without a per-block flag. const accessLogging = options?.accessLogging ?? this.defaults.storageAccessLogging ?? this.defaults.accessLogging; let serverAccessLogsBucket: s3.Bucket | undefined; if (accessLogging) { // The access-log lifecycle expiry derives from the framework-wide // `logRetention` default (a `RetentionDays` enum). `RetentionDays` // is a numeric enum whose member value IS the day count // (ONE_WEEK === 7, ONE_YEAR === 365), so it maps directly to // `Duration.days(...)`. The one non-day member is INFINITE (=== 9999, // "retain forever"): for it we omit the lifecycle rule so logs are // never expired, rather than expiring them at a spurious 9999 days. const logRetention = this.defaults.logRetention; const logLifecycleRules = logRetention === RetentionDays.INFINITE ? undefined : [{ id: 'expire-access-logs', expiration: Duration.days(logRetention) }]; serverAccessLogsBucket = new s3.Bucket(this, 'access-logs', { blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, // Always SSE-S3, even when the data bucket uses SSE-KMS: S3 server // access logging can't deliver to an SSE-KMS target bucket. encryption: s3.BucketEncryption.S3_MANAGED, enforceSSL: true, removalPolicy, autoDeleteObjects: destroy, lifecycleRules: logLifecycleRules, }); } // Object Lock default retention (validated above; requires versioning and a // retained bucket). const objectLock = options?.objectLock; const objectLockDefaultRetention = objectLock ? (objectLock.mode === 'compliance' ? s3.ObjectLockRetention.compliance : s3.ObjectLockRetention.governance)( Duration.days(objectLock.retentionDays), ) : undefined; // Main-bucket lifecycle rules: the noncurrent-version expiration (only // when versioning is on, to bound version-storage growth) merged with // any customer-supplied lifecycle rules into a single array. const lifecycleRules: s3.LifecycleRule[] = []; if (versioned) { lifecycleRules.push({ id: 'ExpireNoncurrentVersions', enabled: true, noncurrentVersionExpiration: Duration.days( options?.noncurrentVersionExpirationDays ?? DEFAULT_NONCURRENT_VERSION_EXPIRATION_DAYS, ), }); } for (const rule of options?.lifecycleRules ?? []) { lifecycleRules.push({ prefix: rule.prefix, expiration: rule.expirationDays ? Duration.days(rule.expirationDays) : undefined, transitions: rule.transitionToIaDays ? [{ storageClass: s3.StorageClass.INFREQUENT_ACCESS, transitionAfter: Duration.days(rule.transitionToIaDays), }] : undefined, }); } this.bucket = new s3.Bucket(this, 'bucket', { bucketName, blockPublicAccess: s3.BlockPublicAccess.BLOCK_ALL, // SSE-KMS buckets enable S3 Bucket Keys, which cut per-request KMS // calls (and their cost) by reusing a bucket-level data key. ...(encryptionKey ? { encryption: s3.BucketEncryption.KMS, encryptionKey, bucketKeyEnabled: true } : { encryption: s3.BucketEncryption.S3_MANAGED }), objectLockDefaultRetention, // All FileBucket traffic (SDK calls + presigned URLs) is HTTPS, so // enforce TLS to close the in-transit exposure gap unconditionally. enforceSSL: true, versioned, removalPolicy, autoDeleteObjects: destroy, serverAccessLogsBucket, serverAccessLogsPrefix: serverAccessLogsBucket ? 'access-logs/' : undefined, cors: options?.corsRules?.map((rule: CorsRule) => ({ allowedOrigins: rule.allowedOrigins, allowedMethods: rule.allowedMethods.map(m => httpMethodMap[m]), allowedHeaders: rule.allowedHeaders, exposedHeaders: rule.exposedHeaders, maxAge: rule.maxAge, })), lifecycleRules: lifecycleRules.length > 0 ? lifecycleRules : undefined, }); // Also grants the runtime role encrypt/decrypt on the bucket's KMS key // (dedicated or imported) when it uses SSE-KMS. this.bucket.grantReadWrite(this.executionRole); } // Runtime-only methods throw during synth (see `synthGuard` in `@aws-blocks/core/cdk`). put(..._args: unknown[]): never { return synthGuard('FileBucket', 'put'); } get(..._args: unknown[]): never { return synthGuard('FileBucket', 'get'); } delete(..._args: unknown[]): never { return synthGuard('FileBucket', 'delete'); } deleteBatch(..._args: unknown[]): never { return synthGuard('FileBucket', 'deleteBatch'); } getUrl(..._args: unknown[]): never { return synthGuard('FileBucket', 'getUrl'); } putUrl(..._args: unknown[]): never { return synthGuard('FileBucket', 'putUrl'); } getFileHandle(..._args: unknown[]): never { return synthGuard('FileBucket', 'getFileHandle'); } createUploadHandle(..._args: unknown[]): never { return synthGuard('FileBucket', 'createUploadHandle'); } scan(..._args: unknown[]): never { return synthGuard('FileBucket', 'scan'); } listVersions(..._args: unknown[]): never { return synthGuard('FileBucket', 'listVersions'); } restoreVersion(..._args: unknown[]): never { return synthGuard('FileBucket', 'restoreVersion'); } }