@cdkd/cli 0.347.0 → 0.349.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ambient-client-defaults-BV_xDm4m.js → ambient-client-defaults-7acjxfyN.js} +3 -3
- package/dist/{ambient-client-defaults-BV_xDm4m.js.map → ambient-client-defaults-7acjxfyN.js.map} +1 -1
- package/dist/{asg-provider-fpr4ZEfp.js → asg-provider-Dvy_jqxt.js} +5 -5
- package/dist/{asg-provider-fpr4ZEfp.js.map → asg-provider-Dvy_jqxt.js.map} +1 -1
- package/dist/aws-partition-DA0r2sr-.js +58 -0
- package/dist/aws-partition-DA0r2sr-.js.map +1 -0
- package/dist/cli.js +2 -2
- package/dist/custom-resource-runtime-Dwnnj7bg.js +1104 -0
- package/dist/custom-resource-runtime-Dwnnj7bg.js.map +1 -0
- package/dist/{db-instance-modify-retry-BbBT68Qa.js → db-instance-modify-retry-pFWx2ED5.js} +4 -4
- package/dist/{db-instance-modify-retry-BbBT68Qa.js.map → db-instance-modify-retry-pFWx2ED5.js.map} +1 -1
- package/dist/delete-started-Co5Gt1jH.js +169 -0
- package/dist/delete-started-Co5Gt1jH.js.map +1 -0
- package/dist/{deploy-engine-DMWjQ_C2.js → deploy-engine-DeYSJno7.js} +720 -11916
- package/dist/deploy-engine-DeYSJno7.js.map +1 -0
- package/dist/diff-calculator-CRkRB1Dg.js +4959 -0
- package/dist/diff-calculator-CRkRB1Dg.js.map +1 -0
- package/dist/ec2-termination-protection-BM1Zt3Fn.js +1277 -0
- package/dist/ec2-termination-protection-BM1Zt3Fn.js.map +1 -0
- package/dist/{ecr-uri-C2FWGsrX.js → ecr-uri-C3_6QVgR.js} +3 -3
- package/dist/{ecr-uri-C2FWGsrX.js.map → ecr-uri-C3_6QVgR.js.map} +1 -1
- package/dist/expected-bucket-owner-CGoY_YS8.js +88 -0
- package/dist/expected-bucket-owner-CGoY_YS8.js.map +1 -0
- package/dist/{iam-role-provider-70-NzlFV.js → iam-role-provider-BaN9MMWs.js} +6 -5
- package/dist/iam-role-provider-BaN9MMWs.js.map +1 -0
- package/dist/image-plan-D4I8-FhR.js +1940 -0
- package/dist/image-plan-D4I8-FhR.js.map +1 -0
- package/dist/index.d.ts +3 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -4
- package/dist/{aws-failure-text-jomzO3aT.js → logger-DmQRya0S.js} +148 -59
- package/dist/logger-DmQRya0S.js.map +1 -0
- package/dist/{neptune-provider-CX4BHKjZ.js → neptune-provider-BYgFNrtZ.js} +6 -6
- package/dist/{neptune-provider-CX4BHKjZ.js.map → neptune-provider-BYgFNrtZ.js.map} +1 -1
- package/dist/{program-BU5T28eB.js → program-BBGm88gl.js} +1031 -2003
- package/dist/program-BBGm88gl.js.map +1 -0
- package/dist/{provider-classes-cw32hLq9.js → provider-classes-CRCHL04N.js} +44 -28
- package/dist/provider-classes-CRCHL04N.js.map +1 -0
- package/dist/{rds-provider-CxSVX1d7.js → rds-provider-DKZjtd50.js} +110 -70
- package/dist/rds-provider-DKZjtd50.js.map +1 -0
- package/dist/{read-replica-DtD9IDko.js → read-replica-C5e4xpYi.js} +78 -24
- package/dist/read-replica-C5e4xpYi.js.map +1 -0
- package/dist/replacement-rules-01_01yDU.js +4937 -0
- package/dist/replacement-rules-01_01yDU.js.map +1 -0
- package/dist/resource-deadline-TfDpwRQ_.js +423 -0
- package/dist/resource-deadline-TfDpwRQ_.js.map +1 -0
- package/dist/{update-removal-CpGaCv-d.js → update-removal-D-FspP88.js} +3 -3
- package/dist/{update-removal-CpGaCv-d.js.map → update-removal-D-FspP88.js.map} +1 -1
- package/dist/{version-Bx-Ox9xU.js → version-DamSnfI_.js} +2 -2
- package/dist/{version-Bx-Ox9xU.js.map → version-DamSnfI_.js.map} +1 -1
- package/package.json +4 -2
- package/dist/aws-failure-text-jomzO3aT.js.map +0 -1
- package/dist/deploy-engine-DMWjQ_C2.js.map +0 -1
- package/dist/iam-role-provider-70-NzlFV.js.map +0 -1
- package/dist/program-BU5T28eB.js.map +0 -1
- package/dist/provider-classes-cw32hLq9.js.map +0 -1
- package/dist/rds-provider-CxSVX1d7.js.map +0 -1
- package/dist/read-replica-DtD9IDko.js.map +0 -1
|
@@ -1,11 +1,19 @@
|
|
|
1
|
-
import { t as getCdkdVersion } from "./version-
|
|
2
|
-
import { $ as
|
|
3
|
-
import { $a as poisonRenderedSpellingsCollidingIn, $d as injectedAwsRegionValue, $i as isFinalSnapshotError, $l as describeRegionValueKind, $n as updatePartialMessage, $o as MULTI_REGION_RECREATE_BLOCKED_TYPES, $r as DEFAULT_RESOURCE_TIMEOUT_MS, $s as refuseMalformedOrphansForDestroy, $t as NESTED_PENDING_PARENT_REASON, $u as warnFinchArgvExposure, A as PROTECTION_PROPERTY_BY_TYPE, Ad as expectedOwnerParam, Ai as withAttemptedItemsMasked, Al as identityKeyFor, An as rollbackOrphanIds, Ao as lacksRecordedTableArn, Ar as retiredNameGenerationsLeaving, As as malformedResourceEntriesWarning, Au as rewriteTemplateAssetReferences, Bd as utf8ByteLength, Bi as secretNamedRecordNeedles, Bl as recordMaskOnlyValue, Bn as propertiesChangedReason, Bo as isNamelessDynamicReferenceError, Br as exportAliasCollisionScrubWarning, Bs as unreadableResourceEntries, Bt as refactorMarkerRefusalMessage, Bu as validateContainerRepoName, C as refusePendingMovesOut, Ca as TemplateNoEchoReresolver, Cc as STATE_RESOURCES_MALFORMED, Cd as CFN_TEMPLATE_BODY_LIMIT, Ci as green, Cl as withPhysicalNameCopies, Cn as DeploymentEventsStore, Cr as removeProtectionTypeList, Cs as refuseMalformedOrphansForOrphan, Cu as AssetPublisher, D as diffSecurity, Da as withPrintingSecrets, Dc as hasReadableResources, Dd as uploadCfnTemplate, Di as noEchoComparisonForTemplate, Dl as isUncertifiedBaselineMaskPosition, Dn as findRefactorHints, Do as AWS_NO_VALUE, Dr as nameScopeOf, Ds as isReadableResourceEntry, Du as buildAssetRedirectMap, E as serviceTokenBlockingReason, Ec as hasReadableOutputs, Ed as findLargeInlineResources, Ei as noEchoAttributeNamesOf, El as dynamicReferenceTokens, En as formatDestructiveChange, Eo as parameterTypeMayLoseSecretIdentity, Er as nameGenerationHighWaterOf, Es as unreadableOrphanRecords, Eu as WorkGraph, Fa as UNSPECIFIED_SKIP_REASON, Fd as AssemblyReader, Fi as namingSecretsWithRecordedNoEcho, Fl as recordPhysicalNameCopy, Fn as differingRemedy, Fo as recordedOutputReferenceRegions, Fr as namesAnyDeclaredParameter, Fs as refuseMalformedResourceEntriesForDestroy, Ft as keptForRetainedRecord, Fu as isCrossRegionRedirect, Gc as isMarkedCoordinate, Gd as ownValue, Gl as wholeStringLeavesOf, Gn as DELETED_RESOURCE_REMEDY, Gr as exportNameNoEchoParameters, Gs as refuseMalformedResourcePropertiesForExport, Gu as describeDockerExecFailure, Hc as DagBuilder, Hd as hasOwnKey, Hi as storedSecretNameNeedles, Hl as recordNoEchoAttributeValues, Hn as referencedLogicalIds, Ho as keepsSecretReferenceToken, Hr as secretBearingStateKeyWarning, Hs as malformedResourcePropertiesWarning, Ht as sameMove, Hu as buildDockerImage, Ia as deleteIndeterminateGuards, Id as StageLoadError, Ii as orphanRecordsPrintingBag, Il as recordNestedStackParameterExpressions, In as isPairableType, Io as recordedReferenceRegions, Ir as reachableDivergentParameters, Is as refuseMalformedResourceEntriesForImport, It as recordRetainedForReadoption, Iu as getBootstrapMarkerKey, Ja as isWaitAbandonedError, Jc as maskWholeValue, Jd as displayAssemblyPath, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jl as LockManager, Jn as withUnprovenUnsettled, Jo as unsettledPropertiesOf, Jr as noEchoParameterValueSeed, Js as UNREADABLE_ORPHANS_CONTAINER_ROW, Ju as redactedDockerCause, Kc as maskAtCoordinates, Kd as absoluteAssemblyPathEscape, Ki as secretSegmentsOfState, Kl as WHOLE_DYNAMIC_REFERENCE_PATTERN, Kn as recordAfterRollbackUpdate, Ko as unsettledItemsField, Kr as exportNameSecretExposure, Ks as refuseMalformedResourcePropertiesForOrphan, Kt as formatResourceLine, Ku as describeDockerFailure, La as deleteLeftInPlace, Ld as processStackMessages, Li as secretNamePrintingBag, Ll as splitGetAttStringForm, Ln as looselyEqual, Lo as getAccountInfo, Lr as resourcesNamingDeclaredParameter, Ls as refuseMalformedResourceEntriesForImportSave, Lt as readRefactorMarker, Lu as parseBootstrapMarker, M as perType, Ma as setResolvedResourceTimeouts, Md as canonicalizeRegion, Mi as completedReplayEntries, Mn as changedReferenceInDiff, Ms as refuseMalformedResourceAttributesForOrphan, Mt as withResourceDeadline, Mu as ensureAssetStorage, N as readProtection, Na as slowCcOperationTimeoutMs, Nc as NO_CC_HANDLERS_REASON, Nd as derivePartitionAndUrlSuffix, Ni as journaledOrphanPrintingBag, Nl as physicalNameCopiesOf, Nn as changedReferencePath, No as keepHeldTokenProvenance, Nr as inheritProducerRegions, Ns as refuseMalformedResourceEntries, Nt as IMPLICIT_DELETE_DEPENDENCIES, Nu as buildDenyExternalAccessPolicy, O as recordedProtectionEvidence, Oc as findActionableSdkUnwired, Od as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, Oi as noEchoExactEchoLeavesOf, Ol as spelledKeysOf, On as hintSidesOf, Oo as cfnRefValueFromPhysicalId, Or as retiredAfterRollback, Os as malformedLocalResourceEntriesWarning, Ou as createAssetRedirectResolver, Pa as RollbackInlinePolicyWriters, Pc as hasNoCloudControlHandlers, Pd as refuseFailedLookups, Pi as maskEventTextWithBoundBags, Pn as changedReferenceReason, Pr as computeParameterTaint, Ps as refuseMalformedResourceEntriesForDeploy, Pt as computeImplicitDeleteEdges, Pu as assertAssetBucketRegion, Qa as isAlwaysLiveAttribute, Qc as noEchoOutputsComparison, Qd as injectAwsRegion, Qi as effectiveDeletionPolicy, Ql as acceptedCreateOnlyDropsOf, Qn as undeclaredEmptyObservedKeys, Qo as shownType, Qr as bindingSkippedOutputs, Qs as refuseMalformedOrphans, Qt as resolvePendingCloudControlRequests, Qu as partitionSensitiveEnv, Ra as deleteSkipReason, Rd as describeJsonParseFailure, Ri as secretNamePrintingBags, Rl as carriesSecretMask, Rn as mappingPairs, Ro as isImpossibleEmptyStoredAttribute, Rr as WITHHELD_NAME_DISPLAY, Rs as refuseMalformedResourceEntriesForOrphan, Rt as readRefactorMarkerOnce, Ru as readBootstrapMarkerBody, S as pendingMovesRefusalMessage, Sa as customResourceResponseExpirationWarning, Sc as withheldAccountClause, Sd as ssmResolvedValueType, Si as gray, Sl as scrubResourceRecord, Sn as DeploymentEventsReader, Sr as segmentCleanupOptions, Ss as refuseMalformedOrphanRecordsForDestroy, Su as withStackInstanceIdWithheld, T as findServiceTokenRefusals, Ta as isCustomResourceType$1, Tc as displayLogicalId, Td as MIGRATE_TMP_PREFIX, Ti as yellow, Tl as DYNAMIC_REFERENCE_TOKEN_SCAN, Tn as findDestructiveChanges, To as isUnboundTemplateParameter, Tr as nameGenerationCarriedFrom, Ts as unpreviewableOrphanRecords, Tu as stringifyValue, Uc as TemplateParser, Ud as hasPlainPrototype, Ui as extractDeploymentEventError, Ul as recordNoEchoParameterFreshValue, Un as replayFailedOperations, Uo as withSharedDrainBudget, Ur as secretSafeKeyDisplay, Us as refuseMalformedResourcePropertiesForDestroy, Ut as updateRefactorMarker, Uu as resolveDockerContextDirectory, Vd as defineOwnKey, Vi as stateSecretNameNeedles, Vl as recordMaskOnlyValuesIn, Vn as proposeRenames, Vo as carriesDynamicReference, Vr as secretBearing, Vs as malformedDriftResourcePropertiesWarning, Vt as refuseRefactorMarker, Vu as BOOTSTRAP_MARKER_PREFIX, Wc as canonicalCoordinates, Wd as nullPrototypeRecord, Wl as recordProvenPublicExpression, Wn as replayRollback, Wo as INTRINSIC_KEYS, Wr as carriedExportAliasExposure, Ws as refuseMalformedResourcePropertiesForDrift, Wu as describeDockerCapturedOutput, Xa as IntrinsicFunctionResolver, Xc as noEchoCoordinatesOf, Xd as resolveAssemblyPath, Xi as ccRoutedFinalSnapshotError, Xl as S3StateBackend, Xn as equalModuloMarkedMask, Xo as withoutUnsettledProperties, Xr as collectPublishedOutputNames, Xs as malformedOrphansRefusalMessage, Xu as dockerSpawnEnvWithSensitive, Ya as DiffCalculator, Yc as maskedLeafCoordinatesOf, Yd as renderAssemblyPathEscape, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yl as isLockInfoExpired, Yn as calculateResourceDrift, Yo as withUnsettledProperties, Yr as collectDeclaredOutputNames, Ys as hasReadableOrphans, Yu as redactDockerArgvValues, Za as isSelectOutOfBounds, Zc as noEchoLeavesOf, Zd as setChildProcessAwsEnv, Zi as ccRoutedInstanceTakesNoSnapshot, Zl as splitImportedOps, Zn as equalModuloMask, Zo as findReplacedReadersOfRecreateTargets, Zr as isExportAliasCollision, Zs as malformedOrphansWarning, Zt as pendingRequestCount, Zu as finchSecretArgvRefusal, _ as listNestedTemplateRows, _a as ccBrokenReason, _c as refuseMalformedResourcesForExport, _d as resolveStateBucketWithDefault, _l as unionOfSecretBags, _n as loadJournaledOrphans, _o as producerRegionsFromState, _r as findNestedStackTypeChanges, _s as malformedOrphanRecordsRefusalMessage, _u as applyCrossPrefixScan, a as scanActiveConsumers, ac as malformedOutputsWarning, ad as runDockerStreaming, ai as withStackRecords, al as redactForState, an as recordDisplacedSkips, ao as applyRoleArnIfSet, au as orphansAfterRollback, b as hasPendingMovesOut, ba as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, bc as JSON_LISTING_HOLE_VALUE, bd as stateBucketExistenceConfirmed, bi as bold, bl as maskSecretsInError, bn as makeSiblingClaimReader, bs as previewableOrphanRecords, bu as isNotImplemented, c as inheritedProvenanceForChildDiff, cc as refuseMalformedOutputsForDestroy, cd as Synthesizer, ci as holdsSupersededResources, cl as carryLogOnlyValues, cn as withNestedRevertRun, co as explicitRoleArnOrThrow, cr as demoteSupersededOrphans, cs as prefetchCreateOnlyPropertyPaths, cu as stackInstanceIdCarriedFrom, d as conditionInputsFrom, dc as refuseDivergentRecordRegionForDestroy, dd as getLegacyStateBucketName, di as supersededHeldByOtherTypeWarning, dl as literalSplitDelimitersOf, dn as withNestedStackContext, do as AWS_CREDENTIAL_ENV_KEYS, dr as planFailedOps, ds as withRetry, du as PhaseClock, ea as refusesFinalSnapshot, ec as repairMalformedOrphansForReadOnly, ed as isDockerClientEnvKey, ei as DEFAULT_RESOURCE_WARN_AFTER_MS, el as readsNoEchoSource, en as displacedOpClause, eo as stackIdTailOf, er as updatePartialReason, es as isStatefulRecreateTargetForReplace, eu as exportNamesCarriedFrom, f as parentSuppliedValues, fc as malformedRenderedContainersWarning, fd as loadCdkJson, fi as supersededHolderOf, fl as logOnlyValueCount, fn as deleteJournaledOrphans, fo as applyCallerIdentityCredentials, fr as recheckFailedPlan, fs as parameterInputsFor, fu as renderPhaseTimings, g as isAbsoluteAssetPath, ga as ProviderRegistry, gc as refuseMalformedResourcesForDestroy, gd as resolveSkipPrefix, gl as shareLogOnlyValues, gn as journaledOrphanLines, go as classifyReplaySecretRegion, gr as withPreviousPolicies, gs as isReadableOrphanRecord, gu as CrossPrefixScanCache, h as findNestedTemplateTreeDefect, ha as CC_BROKEN_REASON, hc as refuseMalformedResourcesForDeploy, hd as resolveCaptureObservedState, hl as recordLogOnlyValue, hn as isHandledOrphan, ho as classifyRecordedSecretRegion, hr as resolveReplacementOldType, hs as deployRefusesOrphanRowsReason, hu as CrossPrefixReadError, i as mergeNoChangeOutputs, ic as malformedOutputsRefusalMessage, id as runDockerForeground, in as nestedChildStackName$1, io as refuseUnreadableCdkCrossAccountRefs, ir as withCreateTokenLedger, iu as isReadableBag, j as isProtectionValueActive, jc as unwrittenCreateOnlyReplacement, jd as PARTITION_TABLE, ji as createReadOnlyAttributeHealerFactory, jl as inheritNestedStackParameterAssociations, jn as withMovedTo, jo as refStateLookupFromResource, jr as withNameGenerationReached, js as malformedScrubResourceEntriesRefusalMessage, ju as AssetModeResolver, k as recordedProtectionNote, ka as CloudControlProvider, kc as findHandledUnwrittenCreateOnly, kd as decodeListingKey, ki as noEchoParameterNamesOf, kl as pathCrossesDottedKey, kn as movedToHint, ko as isStalePlaceholderArnAttribute, kr as retiredNameGenerationsAfter, ks as malformedLocalResourcesWarning, ku as loadPublishableAssetManifest, l as makeCanonicalizePropertiesFn, lc as repairMalformedOutputsForReadOnly, ld as synthesisStatusMessage, li as isSupersededResourceRecord, ll as createUnionSecretMasker, ln as collectNestedChildUnaddressed, lo as isIamRoleArn, lr as isJournaledOrphan, ls as templateResourceTypes, lu as hasReasonlessBaselineRefusal, m as childTemplateLoader, mc as malformedStateRefusalMessage, md as resolveAutoAssetStorage, mi as withoutSuperseded, ml as recordLogOnlyParameterValue, mn as dropFailedHint, mo as envCredentialsAreAssumedRole, mr as replacementNeverSwapped, ms as declaresNoEcho, mu as rebuildClientForBucketRegion, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as malformedExportSourceWarning, nd as formatDockerLoginError, nl as valueAtCoordinate, nn as dropSettledNestedJournals, no as resolveDynamicReferences, nr as ledgerForStack, ns as renderStatefulReason, nu as importableOutputKeys, o as inRunStackKey, od as AssetManifestLoader, oo as assertFlagRoleArn, or as planRollback, ou as orphansCarriedFrom, p as readRecordedConditionVerdicts, pc as malformedResourcesWarning, pd as resolveApp, pi as supersededResourcesOf, pl as printingCorpusOf, pn as dropFailedCommands, po as callerEnvCredentials, pr as recordUnderIdIsNotOwn, pu as timePhase, qc as maskReadbackAtCoordinates, qd as describeFileReadFailure, qi as withSecretPhysicalIdsMaskedInState, ql as isSingleDynamicReferenceToken, qn as settleUnsettledPrevious, qo as unsettledItemsOf, qr as isWholeDynamicReferenceValue, qs as repairMalformedResourcePropertiesForReadOnly, qu as redactedCause, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, rc as malformedLocalOutputsWarning, rd as getDockerCmd, ri as destroyStackRecordsView, rl as liveMatchesUnresolvedTokenFrame, ro as producerLookupOver, ru as importableOutputs, s as crossStackOutputProvenanceSource, sc as refuseMalformedOutputs, sd as getDockerImageBySourceHash, si as deleteSupersededEntry, sn as revertedNestedRowIds, so as assertSendableRoleArn, sr as seedsDeleteFirstGuard, su as shouldRetainResource, t as DeployEngine, ta as unsupportedFinalSnapshotError, tc as malformedExportNamesWarning, td as isMalformedEnvKey, tf as resolveBucketRegion, ti as maskingRetryLogger, tl as recordedNoEchoValuesOf, tn as displacedPhysicalIdShown, ts as isStatefulRecreateTargetSync, tu as hasReadableExportSet, u as conditionFingerprint, uc as STATE_REGION_DIVERGED, ud as getDefaultStateBucketName, ui as supersededAfterRollback, ul as hasMaskableValues, un as getCurrentNestedStackContext, uo as sendableAssumeRoleCommand, ur as isReplacementOrphan, us as describeTypeWithThrottleRetry, uu as hasUnverifiableParameterRefusal, v as renderNestedTemplateTreeDefect, va as isCustomResource, vc as refuseMalformedState, vd as resolveStateBucketWithDefaultAndSource, vl as createSecretMasker, vn as sameJournaledOrphans, vo as regionLessSecretName, vs as malformedOrphanRecordsWarning, vu as crossPrefixDeniedWarning, w as deferredServiceTokenWarning, wa as readsNoEchoDeleteValues, wc as UNREADABLE_RESOURCES_MAP_ROW, wd as CFN_TEMPLATE_URL_LIMIT, wi as red, wn as constructPathOf$1, wo as coerceParameterTypedValue, wr as orphanNeedsIdentity, ws as repairMalformedOrphanRecordsForReadOnly, wu as isSensitiveAttributeName, x as pendingMovesOutOf, xa as applyCustomResourceResponseExpiration, xc as accountArgs, xd as warnDeprecatedNoPrefixCliFlag, xi as cyan, xl as maskSecretsInText, xn as planOrphanAdoption, xs as refuseMalformedOrphanRecords, xu as stackInstanceIdOf, y as templateIdentity, ya as wouldReturnToSdkProvider, yc as repairMalformedResourcesForReadOnly, yd as resolveUseCdkBootstrapAssets, yl as errorCauseChain, yn as makeForeignHolderScan, ys as malformedOrphanRowsKeptWarning, yu as isAccessDenied, zd as parseFailureDebugDetail, zl as provenPublicValue, zn as parseMappingFile, zo as carriesFetchableDynamicReference, zr as displayTextOrWithheld, zs as repairMalformedResourceEntriesForReadOnly, zt as refactorMarkerMovesOf, zu as validateAssetBucketName } from "./deploy-engine-DMWjQ_C2.js";
|
|
4
|
-
import { A as stripControlChars, B as retryClassificationText, Ct as withheldTargetClause, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, J as DynamicReferenceRegionAmbiguousError, Q as AccountIdUnavailableError, R as isRetryableTransientError, St as shellQuote, Tt as setPasteableVerbFlags, U as isThrottlingError, W as markNonRetryable, X as MalformedProducerRecordRefusalError, Y as IntrinsicResolutionRefusalError, _ as ResourceUpdateNotSupportedError, _t as pasteableCommand, a as normalizeAwsError, at as ProvisioningError, bt as quotedOrDescribed, ct as SynthesisError, et as CdkdError, ft as SHELL_ACTIVE_WHY, g as PartialFailureError, gt as isInertUnquoted, h as NestedStackChildDirectDestroyError, i as credentialFingerprint, j as stripForDisplay, k as escapeRegExp, l as withErrorHandling, mt as commandHole, n as ambientCredentialConfig, o as formatError, ot as ResourceTimeoutError, q as CrossAccountSecretRefusalError, r as clientDefaultsFor, rt as LocalInvokeBuildError$1, s as handleError, st as StateError, t as ambientClientDefaults, tt as DeployCancelledError, u as LocalStartServiceError,
|
|
5
|
-
import { $t as forceQuitRecoveryClause, Dt as logicalIdShown, H as assertRegionMatch, M as VALUE_NOT_SHOWN, Qt as buildLockContentionMessage, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Zt as buildForceUnlockCommand, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, bt as interruptWatchListenerCount, dn as setPasteableAwsCaBundle, en as formatLockExpiry, fn as setPasteableAwsProfile, kt as resourceTypeShown, ln as producerCoordinateKey, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mt as isAwsCliLiteral, nn as formatLockOwner, on as DEFAULT_STATE_PREFIX, p as IAM_PRINCIPAL_NAME, pn as withPasteableAwsProfile, sn as injectiveKey, st as runDeleteAttempt, tn as formatLockOperation, un as producerRecordKey, vt as beginCommandInterruptScope, xt as isInterruptedWaitError, y as readRecordedPrincipals, yt as endCommandInterruptScope, z as remedyLogicalId } from "./update-removal-CpGaCv-d.js";
|
|
1
|
+
import { t as getCdkdVersion } from "./version-DamSnfI_.js";
|
|
2
|
+
import { $ as renderUnmatchedPatternsWarning, $t as parseContextOptions, A as followContainerLogs, At as rawCliRegion, B as resolveRuntimeCodeMountPath, Bt as writeProfileCredentialsFile, C as waitForRieReady, Ct as warnAwsEmulatorStateSourceHint, Dt as foldRegionOption, E as SENSITIVE_ENV_KEYS, Et as exportInferredRegionForSdk, F as removeContainer, Ft as resolveEffectiveRegion, G as partitionTopLevel, Gt as contextOptions, H as resolveRuntimeImage, Ht as appOptions, It as stackRegionResolver, J as renderAllNoTopLevelStacks, Jt as destroyOptions, K as refuseStackNameRegionCollisions, Kt as deployOptions, L as runDetached, Lt as stateWithRegion, M as killAndDrainContainerLogs, Mt as reconcileMarkerRegionWithLegacyDefault, N as pickFreePort, Nt as regionNeedsReconciliation, O as ensureDockerAvailable, Ot as legacyStateBucketFallbackRegion, P as pullImage, Pt as regionShown, Q as renderStacksNoLongerSelected, Qt as noLocalCustomResourcesOption, Rt as withOtherIndexRemoval, S as invokeRie, St as taskRoleAssumedInRealAws, T as DockerRunnerError, Tt as adoptDeprecatedRegionFlag, U as describeStack, Ut as applyWaitFlagEnv, V as resolveRuntimeFileExtension, Vt as annotationMessageOptions, W as matchStacks, Wt as commonOptions, X as renderNoStackMatch, Xt as guardStackRegionOptions, Y as renderAmbiguousTargetStack, Yt as exclusivelyOption, Z as renderNotInAppWarning, Zt as noCfnFallbackOption, _ as copyLayerTreeLastWins, _n as listAllLockKeys, _t as prepareLocalLoopbackForwarder, a as materializeLayerFromArn, an as warnIfDeprecatedRegion, at as buildCdkPathIndex, b as probeHostGatewaySupport, bt as resolveContainerRegion, cn as parseAssumeRoleToken, ct as stackForConstructPath, d as resolveAssetCodeDirectory, dn as resourceTimeoutOptions, dt as assertAwsEmulatorValue, en as parseStackRegion, et as selectTargetStack, f as derivePseudoParametersFromRegion$1, fn as validateResourceTimeouts, ft as attachLocalLoopbackForwarder, g as buildContainerImage$1, gn as describeStateKey, gt as mixedModeEmulatorOverride, h as architectureToPlatform, hn as STATE_KEY_MAX_CODE_POINTS, ht as mixedModeActive, i as resolveInlineCodeFilePath, in as useCdkBootstrapAssetsOption, it as unmatchedPatterns, jt as reconcileExportIndexRegion, k as flushStdio, kt as namedCliRegion, l as resolveLambdaLayers, ln as allowUnsupportedTypesOption, lt as stackForPathFormTarget, m as tryResolveImageFnJoin, mn as STATE_FILE_SUFFIX, mt as localAwsEmulatorCredentials, n as resolveTmpfsForLambda, nn as stackOptions, nt as stacksForDependency, o as resolveLambdaTarget, on as effectiveAssumeRoleArn, ot as readCdkPathOrUndefined, p as substituteImagePlaceholders, pn as LOCK_FILE_SUFFIX, pt as getActiveWorkloadAwsWiring$1, q as renderAllLeftOutStageStacks, qt as deprecatedRegionOption, r as resolveZipImagePlan, rn as stateOptions, rt as stacksNoLongerSelected, s as extractEphemeralStorageMb, sn as normalizeStartApiAssumeRole, st as resolveCdkPathToLogicalIds, t as resolveLocalBuildPlan$1, tn as skipFinalSnapshotOption, tt as stackMatchesPattern, u as assetPathDirs, un as parseDuration, ut as activateLocalAwsAndRoleArn, v as layerAssetDirectory, vn as listAllStateKeys, vt as profileCredentialsForWorkload, w as CONTAINER_LOG_DRAIN_TIMEOUT_MS, wt as workloadGetsEmulatorKeysOnly, x as resolveHostGatewayExtraHosts, xt as setContainerRegion, y as HOST_GATEWAY_MIN_VERSION, yn as parseStateKey, yt as realAwsException, z as streamLogs, zt as strandedProfileCredentialsNotice } from "./image-plan-D4I8-FhR.js";
|
|
3
|
+
import { $t as forceQuitRecoveryClause, Dt as logicalIdShown, H as assertRegionMatch, M as VALUE_NOT_SHOWN, Qt as buildLockContentionMessage, U as isMarkedNotGone, V as RESOURCE_NOT_FOUND, Xt as UNREPRODUCIBLE_LOCK_CLAUSE, Zt as buildForceUnlockCommand, an as CUSTOM_RESOURCE_RESPONSE_PREFIX, bt as interruptWatchListenerCount, dn as setPasteableAwsCaBundle, en as formatLockExpiry, fn as setPasteableAwsProfile, kt as resourceTypeShown, ln as producerCoordinateKey, m as RESOLVED_PREVIOUS_PRINCIPAL_KEYS, mt as isAwsCliLiteral, nn as formatLockOwner, on as DEFAULT_STATE_PREFIX, p as IAM_PRINCIPAL_NAME, pn as withPasteableAwsProfile, sn as injectiveKey, st as runDeleteAttempt, tn as formatLockOperation, un as producerRecordKey, vt as beginCommandInterruptScope, xt as isInterruptedWaitError, y as readRecordedPrincipals, yt as endCommandInterruptScope, z as remedyLogicalId } from "./update-removal-D-FspP88.js";
|
|
4
|
+
import { A as stripControlChars, B as retryClassificationText, Ct as withheldTargetClause, F as isAmbiguousOutcomeError, H as isMarkedNonRetryable, J as DynamicReferenceRegionAmbiguousError, Q as AccountIdUnavailableError, R as isRetryableTransientError, St as shellQuote, Tt as setPasteableVerbFlags, U as isThrottlingError, W as markNonRetryable, X as MalformedProducerRecordRefusalError, Y as IntrinsicResolutionRefusalError, _ as ResourceUpdateNotSupportedError, _t as pasteableCommand, a as normalizeAwsError, at as ProvisioningError, bt as quotedOrDescribed, ct as SynthesisError, et as CdkdError, ft as SHELL_ACTIVE_WHY, g as PartialFailureError, gt as isInertUnquoted, h as NestedStackChildDirectDestroyError, i as credentialFingerprint, j as stripForDisplay, k as escapeRegExp, l as withErrorHandling, mt as commandHole, n as ambientCredentialConfig, o as formatError, ot as ResourceTimeoutError, q as CrossAccountSecretRefusalError, r as clientDefaultsFor, rt as LocalInvokeBuildError$1, s as handleError, st as StateError, t as ambientClientDefaults, tt as DeployCancelledError, u as LocalStartServiceError, v as StackHasActiveImportsError, wt as setPasteableRunFlags, xt as shellBoundedDisplay, y as StackTerminationProtectionError, yt as plainOrDescribed, z as isTransientServerError } from "./ambient-client-defaults-7acjxfyN.js";
|
|
6
5
|
import { a as runWithStackAwsClients, i as resetAwsClients, l as s3ClientDefaults, o as setAwsClients, s as resolveS3ClientDefaults, t as AwsClients, u as setS3ClientDefaultsDebugLog } from "./aws-clients-DOkPjjAW.js";
|
|
7
|
-
import { a as
|
|
8
|
-
import { a as
|
|
6
|
+
import { $ as withStackScope, B as generateResourceName, E as coerceCfnBoolean, I as PATTERN_B_NAME_OPTIONS, L as PATTERN_B_NAME_PROPERTIES, Q as withSkipPrefix, R as PATTERN_B_RESOURCE_TYPES, S as explicitNamePropertyFor, X as isNameGeneration, _t as truncateCodePoints, a as reserveStdoutForPayload, at as asIsMessage, ct as displayIdent, dt as isPasteableIdent, gt as terminalSafe, ht as stringifyJsonPayload, i as releaseStdoutForPayload, it as UNRENDERABLE, lt as displaySafe, m as verboseAwareText, mt as safeMsg, n as getLogger, nt as SECRET_REF_MAX_CODE_POINTS, ot as cutMarker, p as safeStringify, pt as plainIdentOr, r as isStdoutReservedForPayload, rt as STACK_REF_MAX_CODE_POINTS, s as runStackBuffered, st as displayAwsMessage, tt as SAFE_MSG_ALTERED_CHAR, u as describeAwsFailure, ut as displayStackName, y as getLiveRenderer, z as derivesPatternBName } from "./logger-DmQRya0S.js";
|
|
7
|
+
import { a as getAssumedRoleCredentials, c as setAssumedRoleCredentials, h as formatAuthority, l as setAwsEndpointOverrideSource, m as runInStackAwsScope, n as awsClientDefaults, r as awsEndpointOverrideActive, s as runWithRealAws } from "./aws-client-defaults-DAebi99J.js";
|
|
8
|
+
import { A as loadCdkJson, B as warnDeprecatedNoPrefixCliFlag, C as runDockerForeground, D as synthesisStatusMessage, E as Synthesizer, F as resolveStateBucketWithDefault, G as uploadCfnTemplate, H as CFN_TEMPLATE_URL_LIMIT, I as resolveStateBucketWithDefaultAndSource, J as AssemblyReader, K as refuseFailedLookups, L as resolveStateBucketWithSource, M as resolveAutoAssetStorage, N as resolveCaptureObservedState, O as getDefaultStateBucketName, P as resolveSkipPrefix, R as resolveUseCdkBootstrapAssets, S as getDockerCmd, T as abortInFlightMultipartUploads, U as MIGRATE_TMP_PREFIX, V as CFN_TEMPLATE_BODY_LIMIT, W as findLargeInlineResources, X as processStackMessages, Y as StageLoadError, Z as setChildProcessAwsEnv, _ as partitionSensitiveEnv, a as AssetPublisher, b as isMalformedEnvKey, c as resolveDockerContextDirectory, d as describeDockerFailure, f as redactedCause, g as finchSecretArgvRefusal, h as dockerSpawnEnvWithSensitive, i as isLockInfoExpired, j as resolveApp, k as getLegacyStateBucketName, m as redactDockerArgvValues, n as DagBuilder, o as WorkGraph, p as redactedDockerCause, r as LockManager, s as buildDockerImage, t as DiffCalculator, u as describeDockerExecFailure, v as warnFinchArgvExposure, w as runDockerStreaming, x as formatDockerLoginError, y as isDockerClientEnvKey, z as stateBucketExistenceConfirmed } from "./diff-calculator-CRkRB1Dg.js";
|
|
9
|
+
import { $a as applyCallerIdentityCredentials, $c as loadPublishableAssetManifest, $i as isFinalSnapshotError, $n as withUnprovenUnsettled, $r as noEchoParameterValueSeed, $s as malformedOutputsWarning, $t as displacedOpClause, A as recordedProtectionEvidence, Aa as UNSPECIFIED_SKIP_REASON, Ac as hasNoCloudControlHandlers, Ai as withAttemptedItemsMasked, Al as nullPrototypeRecord, An as findDestructiveChanges, Ao as isImpossibleEmptyStoredAttribute, Ar as nameGenerationCarriedFrom, As as refuseMalformedResourceEntriesForImportSave, Ba as stackIdTailOf, Bc as applyCrossPrefixScan, Bi as secretNamedRecordNeedles, Bl as resolveBucketRegion, Bn as differingRemedy, Br as namesAnyDeclaredParameter, Bs as refuseMalformedResourcePropertiesForOrphan, Bt as refuseRefactorMarker, C as refusePendingMovesOut, Ca as withPrintingSecrets, Cc as findHandledUnwrittenCreateOnly, Ci as green, Cl as ssmResolvedValueType, Cn as NOECHO_MAC_KEY_ALIAS, Cs as malformedResourceEntriesWarning, D as findServiceTokenRefusals, Di as noEchoComparisonForTemplate, Dl as defineOwnKey, Dn as noEchoMacVerdict, Dr as segmentCleanupOptions, Ds as refuseMalformedResourceEntriesForDeploy, E as deferredServiceTokenWarning, Ei as noEchoAttributeNamesOf, El as decodeListingKey, En as noEchoMacParametersOf, Eo as recordedReferenceRegions, Es as refuseMalformedResourceEntries, F as readProtection, Fa as isWaitAbandonedError, Fc as hasReasonlessBaselineRefusal, Fi as namingSecretsWithRecordedNoEcho, Fl as displayAssemblyPath, Fn as rollbackOrphanIds, Fo as withSharedDrainBudget, Fr as retiredNameGenerationsLeaving, Fs as malformedResourcePropertiesWarning, Ft as recordRetainedForReadoption, Ga as applyRoleArnIfSet, Gc as withStackInstanceIdWithheld, Gn as propertiesChangedReason, Go as MULTI_REGION_RECREATE_BLOCKED_TYPES, Gr as exportAliasCollisionScrubWarning, Gs as malformedOrphansWarning, Gt as formatResourceLine, Ha as resolveDynamicReferences, Hc as isAccessDenied, Hi as storedSecretNameNeedles, Hn as looselyEqual, Ho as findReplacedReadersOfRecreateTargets, Hr as resourcesNamingDeclaredParameter, Hs as UNREADABLE_ORPHANS_CONTAINER_ROW, Ht as updateRefactorMarker, Ia as IntrinsicFunctionResolver, Ic as hasUnverifiableParameterRefusal, Ii as orphanRecordsPrintingBag, In as withMovedTo, Ir as withNameGenerationReached, It as readRefactorMarker, Ja as explicitRoleArnOrThrow, Jc as buildAssetRedirectMap, Ji as ATOMIC_FINAL_SNAPSHOT_TYPES, Jn as replayFailedOperations, Jo as renderStatefulReason, Jr as secretSafeKeyDisplay, Js as repairMalformedOrphansForReadOnly, Ka as assertFlagRoleArn, Kc as isSensitiveAttributeName, Ki as secretSegmentsOfState, Kn as proposeRenames, Ko as isStatefulRecreateTargetForReplace, Kr as secretBearing, Ks as refuseMalformedOrphans, La as isSelectOutOfBounds, Lc as rebuildClientForBucketRegion, Li as secretNamePrintingBag, Ll as renderAssemblyPathEscape, Ln as changedReferenceInDiff, Lo as INTRINSIC_KEYS, Ls as refuseMalformedResourcePropertiesForDestroy, Lt as readRefactorMarkerOnce, M as PROTECTION_PROPERTY_BY_TYPE, Ma as deleteLeftInPlace, Mc as S3StateBackend, Mi as completedReplayEntries, Mn as findRefactorHints, Mo as isNamelessDynamicReferenceError, Mr as nameScopeOf, Ms as repairMalformedResourceEntriesForReadOnly, Mt as IMPLICIT_DELETE_DEPENDENCIES, N as isProtectionValueActive, Na as deleteSkipReason, Nc as splitImportedOps, Ni as journaledOrphanPrintingBag, Nn as hintSidesOf, No as carriesDynamicReference, Nr as retiredAfterRollback, Ns as unreadableResourceEntries, Nt as computeImplicitDeleteEdges, O as serviceTokenBlockingReason, Oa as setResolvedResourceTimeouts, Oi as noEchoExactEchoLeavesOf, Ol as hasOwnKey, On as noEchoValueMacsOf, Or as removeProtectionTypeList, Os as refuseMalformedResourceEntriesForDestroy, P as perType, Pi as maskEventTextWithBoundBags, Pl as describeFileReadFailure, Pn as movedToHint, Po as keepsSecretReferenceToken, Pr as retiredNameGenerationsAfter, Ps as malformedDriftResourcePropertiesWarning, Pt as keptForRetainedRecord, Qa as AWS_CREDENTIAL_ENV_KEYS, Qi as effectiveDeletionPolicy, Qn as settleUnsettledPrevious, Qr as isWholeDynamicReferenceValue, Qs as malformedOutputsRefusalMessage, Qt as NESTED_PENDING_PARENT_REASON, Ra as isAlwaysLiveAttribute, Rc as CrossPrefixReadError, Ri as secretNamePrintingBags, Rl as resolveAssemblyPath, Rn as changedReferencePath, Rr as inheritProducerRegions, Rs as refuseMalformedResourcePropertiesForDrift, Rt as refactorMarkerMovesOf, S as pendingMovesRefusalMessage, Sc as findActionableSdkUnwired, Si as gray, Sn as DeploymentEventsStore, So as keepHeldTokenProvenance, Sr as findNestedStackTypeChanges, Ss as malformedLocalResourcesWarning, T as readsOnlyNoEchoParameters, Ta as CloudControlProvider, Tc as unwrittenCreateOnlyReplacement, Ti as yellow, Tn as noEchoMacBinding, Ts as refuseMalformedResourceAttributesForOrphan, Ua as producerLookupOver, Uc as isNotImplemented, Ui as extractDeploymentEventError, Un as mappingPairs, Ur as WITHHELD_NAME_DISPLAY, Us as hasReadableOrphans, Vc as crossPrefixDeniedWarning, Vi as stateSecretNameNeedles, Vn as isPairableType, Vr as reachableDivergentParameters, Vs as repairMalformedResourcePropertiesForReadOnly, Vt as sameMove, Wa as refuseUnreadableCdkCrossAccountRefs, Wc as stackInstanceIdOf, Wn as parseMappingFile, Wo as shownType, Wr as displayTextOrWithheld, Ws as malformedOrphansRefusalMessage, Xa as parseIamRoleArn, Xi as ccRoutedFinalSnapshotError, Xn as DELETED_RESOURCE_REMEDY, Xr as exportNameNoEchoParameters, Xs as malformedExportSourceWarning, Xt as pendingRequestCount, Ya as isIamRoleArn, Yc as createAssetRedirectResolver, Yi as PRE_DELETE_SNAPSHOT_TYPES, Yn as replayRollback, Yr as carriedExportAliasExposure, Ys as malformedExportNamesWarning, Za as sendableAssumeRoleCommand, Zi as ccRoutedInstanceTakesNoSnapshot, Zn as recordAfterRollbackUpdate, Zr as exportNameSecretExposure, Zs as malformedLocalOutputsWarning, Zt as resolvePendingCloudControlRequests, _ as listNestedTemplateRows, _a as customResourceResponseExpirationWarning, _c as STATE_RESOURCES_MALFORMED, _i as supersededHolderOf, _n as sameJournaledOrphans, _o as lacksRecordedTableArn, _r as recheckFailedPlan, _s as repairMalformedOrphanRecordsForReadOnly, a as scanActiveConsumers, aa as ProviderRegistry, ac as refuseDivergentRecordRegionForDestroy, ai as DEFAULT_RESOURCE_WARN_AFTER_MS, al as buildDenyExternalAccessPolicy, ao as regionLessSecretName, ar as updatePartialReason, b as hasPendingMovesOut, ba as readsNoEchoDeleteValues, bc as hasReadableOutputs, bi as bold, bn as planOrphanAdoption, br as resolveReplacementOldType, bs as isReadableResourceEntry, c as inheritedProvenanceForChildDiff, ca as wouldReturnToSdkProvider, cc as malformedStateRefusalMessage, ci as destroyStackRecordsView, cl as getBootstrapMarkerKey, cn as collectNestedChildUnaddressed, cs as deployRefusesOrphanRowsReason, d as conditionInputsFrom, dc as refuseMalformedResourcesForExport, dl as validateAssetBucketName, dn as deleteJournaledOrphans, do as coerceParameterTypedValue, dr as planRollback, ds as malformedOrphanRecordsWarning, ea as refusesFinalSnapshot, ei as collectDeclaredOutputNames, en as displacedPhysicalIdShown, eo as callerEnvCredentials, er as calculateResourceDrift, f as parentSuppliedValues, fc as refuseMalformedState, fi as deleteSupersededEntry, fl as validateContainerRepoName, fn as dropFailedCommands, fo as isUnboundTemplateParameter, fr as seedsDeleteFirstGuard, fs as malformedOrphanRowsKeptWarning, g as isAbsoluteAssetPath, ga as applyCustomResourceResponseExpiration, gc as withheldAccountClause, gi as supersededHeldByOtherTypeWarning, gn as loadJournaledOrphans, go as isStalePlaceholderArnAttribute, gr as planFailedOps, gs as refuseMalformedOrphansForOrphan, h as findNestedTemplateTreeDefect, ha as CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID, hc as accountArgs, hi as supersededAfterRollback, hl as getDockerImageBySourceHash, hn as journaledOrphanLines, ho as cfnRefValueFromPhysicalId, hr as isReplacementOrphan, hs as refuseMalformedOrphanRecordsForDestroy, i as mergeNoChangeOutputs, ia as CC_BROKEN_REASON, ic as STATE_REGION_DIVERGED, ii as DEFAULT_RESOURCE_TIMEOUT_MS, il as ensureAssetStorage, in as recordDisplacedSkips, io as producerRegionsFromState, ir as updatePartialMessage, is as parameterInputsFor, j as recordedProtectionNote, ja as deleteIndeterminateGuards, jc as TemplateParser, ji as createReadOnlyAttributeHealerFactory, jl as ownValue, jn as formatDestructiveChange, jo as carriesFetchableDynamicReference, jr as nameGenerationHighWaterOf, js as refuseMalformedResourceEntriesForOrphan, k as diffSecurity, ka as RollbackInlinePolicyWriters, kc as NO_CC_HANDLERS_REASON, ki as noEchoParameterNamesOf, kl as hasPlainPrototype, kn as constructPathOf$1, ko as getAccountInfo, kr as orphanNeedsIdentity, ks as refuseMalformedResourceEntriesForImport, l as makeCanonicalizePropertiesFn, lc as refuseMalformedResourcesForDeploy, ll as parseBootstrapMarker, ln as getCurrentNestedStackContext, lr as withCreateTokenLedger, ls as isReadableOrphanRecord, m as childTemplateLoader, ma as withCustomResourceStack, mc as JSON_LISTING_HOLE_VALUE, mi as isSupersededResourceRecord, ml as AssetManifestLoader, mn as isHandledOrphan, mo as AWS_NO_VALUE, mr as isJournaledOrphan, ms as refuseMalformedOrphanRecords, n as isSecretBearingReferenceString, na as createPreDeleteFinalSnapshot, nc as refuseMalformedOutputsForDestroy, ni as isExportAliasCollision, nl as rewriteTemplateAssetReferences, no as classifyRecordedSecretRegion, nr as equalModuloMask, ns as maskedPropertyFingerprintsOf, o as inRunStackKey, oa as ccBrokenReason, oc as malformedRenderedContainersWarning, oi as maskingRetryLogger, ol as assertAssetBucketRegion, on as revertedNestedRowIds, os as declaresNoEcho, p as readRecordedConditionVerdicts, pa as setLocalCustomResourceRuntimeEnabled, pc as repairMalformedResourcesForReadOnly, pi as holdsSupersededResources, pl as BOOTSTRAP_MARKER_PREFIX, pn as dropFailedHint, po as parameterTypeMayLoseSecretIdentity, pr as demoteSupersededOrphans, ps as previewableOrphanRecords, qa as assertSendableRoleArn, qi as withSecretPhysicalIdsMaskedInState, qn as referencedLogicalIds, qo as isStatefulRecreateTargetSync, qr as secretBearingStateKeyWarning, qs as refuseMalformedOrphansForDestroy, r as keptWholeReasonText, ra as buildFinalSnapshotIdentifier, rc as repairMalformedOutputsForReadOnly, ri as bindingSkippedOutputs, rl as AssetModeResolver, rn as nestedChildStackName$1, ro as classifyReplaySecretRegion, rr as undeclaredEmptyObservedKeys, s as crossStackOutputProvenanceSource, sa as isCustomResource, sc as malformedResourcesWarning, sl as isCrossRegionRedirect, sn as withNestedRevertRun, sr as ledgerForStack, ss as maskedPropertyFingerprint, t as DeployEngine, ta as unsupportedFinalSnapshotError, tc as refuseMalformedOutputs, ti as collectPublishedOutputNames, tn as dropSettledNestedJournals, to as envCredentialsAreAssumedRole, tr as equalModuloMarkedMask, u as conditionFingerprint, uc as refuseMalformedResourcesForDestroy, ui as withStackRecords, ul as readBootstrapMarkerBody, un as withNestedStackContext, us as malformedOrphanRecordsRefusalMessage, v as renderNestedTemplateTreeDefect, vc as UNREADABLE_RESOURCES_MAP_ROW, vi as supersededResourcesOf, vn as makeForeignHolderScan, vo as refStateLookupFromResource, vr as recordUnderIdIsNotOwn, vs as unpreviewableOrphanRecords, w as macWriteOnlyKeys, wi as red, wl as CUSTOM_RESOURCE_RESPONSE_OBJECT_DESCRIPTION, wn as createNoEchoValueMacs, wo as recordedOutputReferenceRegions, ws as malformedScrubResourceEntriesRefusalMessage, x as pendingMovesOutOf, xa as isCustomResourceType$1, xc as hasReadableResources, xi as cyan, xn as DeploymentEventsReader, xr as withPreviousPolicies, xs as malformedLocalResourceEntriesWarning, y as templateIdentity, ya as TemplateNoEchoReresolver, yc as displayLogicalId, yi as withoutSuperseded, yn as makeSiblingClaimReader, yr as replacementNeverSwapped, ys as unreadableOrphanRecords, za as poisonRenderedSpellingsCollidingIn, zc as CrossPrefixScanCache, zn as changedReferenceReason, zr as computeParameterTaint, zs as refuseMalformedResourcePropertiesForExport, zt as refactorMarkerRefusalMessage } from "./deploy-engine-DeYSJno7.js";
|
|
10
|
+
import { n as canonicalizeRegion, r as derivePartitionAndUrlSuffix, t as PARTITION_TABLE } from "./aws-partition-DA0r2sr-.js";
|
|
11
|
+
import { A as parseFailureDebugDetail, E as timePhase, M as utf8ByteLength, O as describeJsonParseFailure, T as renderPhaseTimings, d as getCreateOnlyPropertyPaths, g as describeTypeWithThrottleRetry, m as templateResourceTypes, p as prefetchCreateOnlyPropertyPaths, x as PhaseClock, y as withRetry } from "./ec2-termination-protection-BM1Zt3Fn.js";
|
|
12
|
+
import { t as expectedOwnerParam } from "./expected-bucket-owner-CGoY_YS8.js";
|
|
13
|
+
import { a as acceptedCreateOnlyDropsOf, c as hasReadableExportSet, d as isReadableBag, f as orphansAfterRollback, g as stackInstanceIdCarriedFrom, i as slowCcOperationTimeoutMs, l as importableOutputKeys, m as shouldRetainResource, o as describeRegionValueKind, p as orphansCarriedFrom, s as exportNamesCarriedFrom, u as importableOutputs } from "./delete-started-Co5Gt1jH.js";
|
|
14
|
+
import { An as recordProvenPublicExpression, Cn as provenPublicValue, D as recordedNoEchoValuesOf, Dn as recordMaskOnlyValuesIn, En as recordMaskOnlyValue, Fn as isSingleDynamicReferenceToken, Ft as spelledKeysOf, It as pathCrossesDottedKey, Mt as DYNAMIC_REFERENCE_TOKEN_SCAN, Nn as WHOLE_DYNAMIC_REFERENCE_PATTERN, Nt as dynamicReferenceTokens, On as recordNoEchoAttributeValues, Ot as scrubResourceRecord, Pt as isUncertifiedBaselineMaskPosition, Rt as identityKeyFor, T as readsNoEchoSource, W as redactForState, _t as maskSecretsInText, an as physicalNameCopiesOf, at as literalSplitDelimitersOf, b as noEchoOutputsComparison, cn as recordNestedStackParameterExpressions, ct as recordLogOnlyParameterValue, dn as splitGetAttStringForm, dt as shareLogOnlyValues, et as carryLogOnlyValues, f as isMarkedCoordinate, fn as carriesSecretMask, ft as unionOfSecretBags, g as maskedLeafCoordinatesOf, gt as maskSecretsInError, h as maskWholeValue, it as hasMaskableValues, j as liveMatchesUnresolvedTokenFrame, jn as wholeStringLeavesOf, k as valueAtCoordinate, kn as recordNoEchoParameterFreshValue, kt as withPhysicalNameCopies, m as maskReadbackAtCoordinates, mt as errorCauseChain, nt as createUnionSecretMasker, ot as logOnlyValueCount, p as maskAtCoordinates, pt as createSecretMasker, qt as inheritNestedStackParameterAssociations, sn as recordPhysicalNameCopy, st as printingCorpusOf, u as canonicalCoordinates, ut as recordLogOnlyValue, v as noEchoCoordinatesOf, y as noEchoLeavesOf } from "./replacement-rules-01_01yDU.js";
|
|
15
|
+
import { D as withoutUnsettledProperties, E as withUnsettledProperties, S as unsettledItemsOf, i as withResourceDeadline, w as unsettledPropertiesOf, x as unsettledItemsField } from "./resource-deadline-TfDpwRQ_.js";
|
|
16
|
+
import { a as parseEcrRegistryHost, i as looksLikeEcrHostWithForeignSuffix, n as hasEcrRegistryHostLabels, t as ecrRegistryHostPattern } from "./ecr-uri-C3_6QVgR.js";
|
|
9
17
|
import { t as cdkdCacheHome } from "./cli.js";
|
|
10
18
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
11
19
|
import { CopyObjectCommand, CreateBucketCommand, DeleteBucketCommand, DeleteObjectsCommand, GetBucketLocationCommand, GetObjectCommand, HeadBucketCommand, ListObjectVersionsCommand, ListObjectsV2Command, NoSuchBucket, NotFound, PutBucketEncryptionCommand, PutBucketPolicyCommand, PutBucketVersioningCommand, PutObjectCommand, S3Client, S3ServiceException } from "@aws-sdk/client-s3";
|
|
@@ -17,492 +25,24 @@ import { GetSecretValueCommand, SecretsManagerClient } from "@aws-sdk/client-sec
|
|
|
17
25
|
import { GetParameterCommand, SSMClient } from "@aws-sdk/client-ssm";
|
|
18
26
|
import { DescribeLogStreamsCommand, ResourceNotFoundException as ResourceNotFoundException$1 } from "@aws-sdk/client-cloudwatch-logs";
|
|
19
27
|
import * as fs from "node:fs";
|
|
20
|
-
import {
|
|
28
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, promises, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
21
29
|
import * as path from "node:path";
|
|
22
30
|
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
23
|
-
import { execFile
|
|
31
|
+
import { execFile } from "node:child_process";
|
|
24
32
|
import { devNull, tmpdir } from "node:os";
|
|
33
|
+
import { CreateAliasCommand, CreateKeyCommand, DescribeKeyCommand, KMSClient, ScheduleKeyDeletionCommand } from "@aws-sdk/client-kms";
|
|
25
34
|
import { BatchDeleteImageCommand, DeleteRepositoryCommand, DescribeImagesCommand as DescribeImagesCommand$1, ECRClient, GetAuthorizationTokenCommand } from "@aws-sdk/client-ecr";
|
|
35
|
+
import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, DEFAULT_AWS_EMULATOR_URL, DynamicReferenceResolver, EMULATOR_SCRUBBED_ENV_KEYS, EcsTaskResolutionError, MCP_CONTAINER_PORT, MCP_PATH, UNNAMED_WORKLOAD, a2aInvokeOnce, addAlbSpecificOptions, addAwsEndpointOptions, addCommonEcsServiceOptions, addImageOverrideOptions, addStartServiceSpecificOptions, albStrategy, applyWorkloadAwsWiringToEnv, attachAuthorizers, attachStageContext, availableApiIdentifiers, awaitLoopbackForwarderStatus, awsEmulatorEnvName, awsEmulatorRealServices, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildNamespaceOwnerForwarderDockerArgs, buildStageMap, canonicalizeImageOverrideKeys, classifySourceChange, containsDynamicReference, createAuthorizerCache, createFileWatcher, createFileWatcher as createFileWatcher$1, createJwksCache, createMixedModeStateProvider, createWatchPredicates, defaultCredentialsLoader, describeAwsFailureForWarn, describeForwarderFailure, discoverRoutes, discoverWebSocketApis, dockerRegistryEnv, downloadAndExtractS3Bundle, effectiveLoopbackPorts, enforceImageOverrideOrphans, filterRoutesByApiIdentifier, firstUsableRegion, getActiveWorkloadAwsWiring, getAwsEndpointOverride, groupRoutesByServer, groupWorkloadsRoutedApart, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isAwsServiceRoutedToEmulator, keysNotFromTemplate, keysOverriddenBy, loopbackForwarderPlan, mcpInvokeOnce, noImplicitEcrPullArgs, parseAwsEndpoint, parseConnectionsPath, parseImageOverrideFlags, parseSelectionExpressionPath, pickAgentCoreCandidateStack, pickAgentCoreCandidateStack as pickAgentCoreCandidateStack$1, readAwsEmulatorEnvVarsFile, readEmulatorRunFiles, readEnvVarsFileText, readMtlsMaterialsFromDisk, realAwsServicesOf, resolveAgentCoreTarget, resolveAwsEmulatorOption, resolveDynamicReferencesInEnv, resolveEnvVars, resolveHostDefaultCredentials, resolveImageOverrides, resolveSingleTarget, resolveWatchConfig, resolveWorkloadAwsWiring, runEcsServiceEmulator, runImageOverrideBuilds, setActiveWorkloadAwsWiring, setAwsEndpointOverride, signAgentCoreInvocation, startApiServer, verifyJwtViaDiscovery, waitForAgentCorePing, withoutKeys } from "cdk-local/internal";
|
|
26
36
|
import { isDeepStrictEqual, promisify } from "node:util";
|
|
27
37
|
import graphlib from "graphlib";
|
|
28
38
|
import { Command, InvalidArgumentError, Option } from "commander";
|
|
29
|
-
import { A2A_CONTAINER_PORT, A2A_PATH, AGENTCORE_A2A_PROTOCOL, AGENTCORE_AGUI_PROTOCOL, AGENTCORE_MCP_PROTOCOL, ConnectionRegistry, DEFAULT_AWS_EMULATOR_URL, DynamicReferenceResolver, EMULATOR_SCRUBBED_ENV_KEYS, EcsTaskResolutionError, HOST_GATEWAY_MIN_VERSION, LocalInvokeBuildError, MCP_CONTAINER_PORT, MCP_PATH, UNNAMED_WORKLOAD, a2aInvokeOnce, activateWorkloadAwsWiring, addAlbSpecificOptions, addAwsEndpointOptions, addCommonEcsServiceOptions, addImageOverrideOptions, addStartServiceSpecificOptions, albStrategy, applyWorkloadAwsWiringToEnv, architectureToPlatform, attachAuthorizers, attachLoopbackForwarder, attachStageContext, availableApiIdentifiers, awaitLoopbackForwarderStatus, awsEmulatorEnvName, awsEmulatorRealServices, bufferToBody, buildAgentCoreCodeImage, buildCognitoJwksUrl, buildConnectEvent, buildContainerImage, buildCorsConfigByApiId, buildCorsConfigFromCloudFrontChain, buildDisconnectEvent, buildJwksUrlFromIssuer, buildMessageEvent, buildMgmtEndpointEnvUrl, buildNamespaceOwnerForwarderDockerArgs, buildStageMap, canonicalizeImageOverrideKeys, classifySourceChange, containsDynamicReference, createAuthorizerCache, createFileWatcher, createFileWatcher as createFileWatcher$1, createJwksCache, createMixedModeStateProvider, createWatchPredicates, defaultCredentialsLoader, derivePseudoParametersFromRegion, describeAwsFailureForWarn, describeForwarderFailure, discoverRoutes, discoverWebSocketApis, downloadAndExtractS3Bundle, effectiveLoopbackPorts, enforceImageOverrideOrphans, ensureForwarderImage, filterRoutesByApiIdentifier, firstUsableRegion, getActiveWorkloadAwsWiring, getActiveWorkloadAwsWiring as getActiveWorkloadAwsWiring$1, getAwsEndpointOverride, groupRoutesByServer, groupWorkloadsRoutedApart, handleConnectionsRequest, invokeAgentCore, invokeAgentCoreWs, isAwsServiceRoutedToEmulator, isRealAwsSentinel, keysNotFromTemplate, keysOverriddenBy, loopbackForwarderPlan, materializeLayerFromArn, mcpInvokeOnce, parseAwsEndpoint, parseConnectionsPath, parseImageOverrideFlags, parseSelectionExpressionPath, pickAgentCoreCandidateStack, pickAgentCoreCandidateStack as pickAgentCoreCandidateStack$1, probeHostGatewaySupport, readAwsEmulatorEnvVarsFile, readEmulatorRunFiles, readEnvVarsFileText, readMtlsMaterialsFromDisk, realAwsServicesOf, recordAssumedRole, resolveAgentCoreTarget, resolveAwsEmulatorOption, resolveDynamicReferencesInEnv, resolveEnvVars, resolveHostDefaultCredentials, resolveHostGatewayExtraHosts, resolveImageOverrides, resolveRuntimeCodeMountPath, resolveRuntimeFileExtension, resolveRuntimeImage, resolveSingleTarget, resolveWatchConfig, resolveWorkloadAwsWiring, runEcsServiceEmulator, runImageOverrideBuilds, setActiveWorkloadAwsWiring, setAwsEndpointOverride, signAgentCoreInvocation, startApiServer, substituteImagePlaceholders, takeAwsEmulatorStateSourceHint, tryResolveImageFnJoin, verifyJwtViaDiscovery, waitForAgentCorePing, withoutKeys } from "cdk-local/internal";
|
|
30
|
-
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
|
31
39
|
import * as readline$1 from "node:readline/promises";
|
|
32
40
|
import readline from "node:readline/promises";
|
|
33
41
|
import { Document, Pair, Scalar, YAMLError, YAMLMap, YAMLSeq, isScalar, parse, parseDocument, stringify, visit } from "yaml";
|
|
34
42
|
import { emitKeypressEvents } from "node:readline";
|
|
35
43
|
import { createLocalStartAgentCoreCommand, createLocalStartCloudFrontCommand, createLocalStartMicrovmCommand, createLocalStartWebFunctionCommand, createLocalStateProvider, getEmbedConfig, isCfnFlagPresent, listTargets, rejectExplicitCfnStackWithMultipleStacks, resolveCfnFallbackRegion, setEmbedConfig, substituteAgainstState, substituteAgainstStateAsync, substituteEnvVarsFromState, substituteEnvVarsFromStateAsync } from "cdk-local";
|
|
36
|
-
import { createServer } from "node:net";
|
|
37
|
-
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
38
44
|
import { WebSocketServer } from "ws";
|
|
39
45
|
|
|
40
|
-
// src/cli/commands/state-file-keys.ts
|
|
41
|
-
const STATE_FILE_SUFFIX = "/state.json";
|
|
42
|
-
const LEGACY_SEGMENTS_UNDER_PREFIX = 1;
|
|
43
|
-
const LOCK_FILE_SUFFIX = "/lock.json";
|
|
44
|
-
const REGION_SEGMENT = /^(?:[a-z]{2}|eusc)(-[a-z]+)+-\d+$/;
|
|
45
|
-
async function listAllStateKeys(stateBackend) {
|
|
46
|
-
return (await stateBackend.listRawKeys("")).filter((k) => k.endsWith(STATE_FILE_SUFFIX));
|
|
47
|
-
}
|
|
48
|
-
async function listAllLockKeys(stateBackend) {
|
|
49
|
-
return (await stateBackend.listRawKeys("")).filter((k) => k.endsWith(LOCK_FILE_SUFFIX));
|
|
50
|
-
}
|
|
51
|
-
function parseStateKey(key, suffix = STATE_FILE_SUFFIX, knownPrefix) {
|
|
52
|
-
const body = key.slice(0, -suffix.length);
|
|
53
|
-
const prefix = knownPrefix?.replace(/\/+$/, "");
|
|
54
|
-
if (prefix !== void 0 && prefix !== "" && key.startsWith(`${prefix}/`)) {
|
|
55
|
-
const rest = body.slice(prefix.length + 1).split("/");
|
|
56
|
-
if (rest.length === LEGACY_SEGMENTS_UNDER_PREFIX && rest[0]) return { stack: rest[0] };
|
|
57
|
-
}
|
|
58
|
-
const segments = body.split("/");
|
|
59
|
-
const last = segments[segments.length - 1] ?? key;
|
|
60
|
-
const secondLast = segments[segments.length - 2];
|
|
61
|
-
if (secondLast !== void 0 && secondLast !== "" && REGION_SEGMENT.test(last)) return {
|
|
62
|
-
stack: secondLast,
|
|
63
|
-
region: last
|
|
64
|
-
};
|
|
65
|
-
return { stack: last };
|
|
66
|
-
}
|
|
67
|
-
function describeStateKey(key, suffix = STATE_FILE_SUFFIX, knownPrefix) {
|
|
68
|
-
const { stack, region } = parseStateKey(key, suffix, knownPrefix);
|
|
69
|
-
const name = displayIdent(stack, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
|
|
70
|
-
return region === void 0 ? name : `${name} (${displayIdent(region)})`;
|
|
71
|
-
}
|
|
72
|
-
const STATE_KEY_MAX_CODE_POINTS = STACK_REF_MAX_CODE_POINTS + 64;
|
|
73
|
-
|
|
74
|
-
// src/cli/options/resource-timeout.ts
|
|
75
|
-
function parseDuration(value) {
|
|
76
|
-
if (typeof value !== "string" || value.length === 0) throw new Error(`Invalid duration "${value}": expected <number>s, <number>m, or <number>h (e.g. 30s, 5m, 1h)`);
|
|
77
|
-
const match = /^(\d+(?:\.\d+)?)([smh])$/.exec(value.trim());
|
|
78
|
-
if (!match) throw new Error(`Invalid duration "${value}": expected <number>s, <number>m, or <number>h (e.g. 30s, 5m, 1h)`);
|
|
79
|
-
const num = Number(match[1]);
|
|
80
|
-
if (!Number.isFinite(num) || num <= 0) throw new Error(`Invalid duration "${value}": must be greater than zero`);
|
|
81
|
-
const unit = match[2];
|
|
82
|
-
return Math.round(num * (unit === "s" ? 1e3 : unit === "m" ? 6e4 : 36e5));
|
|
83
|
-
}
|
|
84
|
-
const RESOURCE_TYPE_REGEX = TIMEOUT_FLAG_RESOURCE_TYPE;
|
|
85
|
-
function parseResourceTimeoutToken(flagName) {
|
|
86
|
-
return (raw, previous) => {
|
|
87
|
-
const acc = previous ?? { perTypeMs: {} };
|
|
88
|
-
if (!acc.perTypeMs) acc.perTypeMs = {};
|
|
89
|
-
const eqIndex = raw.indexOf("=");
|
|
90
|
-
if (eqIndex === -1) {
|
|
91
|
-
acc.globalMs = parseDuration(raw);
|
|
92
|
-
return acc;
|
|
93
|
-
}
|
|
94
|
-
const typePart = raw.substring(0, eqIndex).trim();
|
|
95
|
-
const durationPart = raw.substring(eqIndex + 1).trim();
|
|
96
|
-
if (!RESOURCE_TYPE_REGEX.test(typePart)) throw new Error(`Invalid ${flagName} value "${raw}": left-hand side must be a CloudFormation resource type like AWS::Service::Resource (got "${typePart}")`);
|
|
97
|
-
if (durationPart.length === 0) throw new Error(`Invalid ${flagName} value "${raw}": missing duration after '=' (e.g. ${typePart}=1h)`);
|
|
98
|
-
let ms;
|
|
99
|
-
try {
|
|
100
|
-
ms = parseDuration(durationPart);
|
|
101
|
-
} catch (err) {
|
|
102
|
-
const inner = describeAwsFailure(err).detail;
|
|
103
|
-
throw new Error(`Invalid ${flagName} value "${raw}": ${inner}`);
|
|
104
|
-
}
|
|
105
|
-
acc.perTypeMs[typePart] = ms;
|
|
106
|
-
return acc;
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
const resourceTimeoutOptions = [new Option("--resource-warn-after <duration_or_type=duration>", "Warn when a single resource operation exceeds this wall-clock duration. Repeatable: pass a bare duration (e.g. 5m) to set the global default, or TYPE=DURATION (e.g. AWS::CloudFront::Distribution=10m) for a per-type override.").default(void 0, "5m").argParser(parseResourceTimeoutToken("--resource-warn-after")), new Option("--resource-timeout <duration_or_type=duration>", "Abort a single resource operation that exceeds this wall-clock duration. Repeatable: pass a bare duration (e.g. 30m) to set the global default, or TYPE=DURATION (e.g. AWS::CloudFront::Distribution=1h) for a per-type override. Custom-Resource-heavy stacks may need to raise this above the default 30m (the Custom Resource provider's polling cap is 1h). When this is shorter than the 5m --resource-warn-after default, --resource-warn-after is auto-lowered to min(5m, 0.5*timeout) and a warning is logged so the user can override explicitly.").default(void 0, "30m").argParser(parseResourceTimeoutToken("--resource-timeout"))];
|
|
110
|
-
function formatMs(ms) {
|
|
111
|
-
if (ms % 36e5 === 0) return `${ms / 36e5}h`;
|
|
112
|
-
if (ms % 6e4 === 0) return `${ms / 6e4}m`;
|
|
113
|
-
return `${Math.round(ms / 1e3)}s`;
|
|
114
|
-
}
|
|
115
|
-
function autoLoweredWarnMs(timeoutMs) {
|
|
116
|
-
return Math.max(1, Math.min(DEFAULT_RESOURCE_WARN_AFTER_MS, Math.floor(timeoutMs / 2)));
|
|
117
|
-
}
|
|
118
|
-
function validateResourceTimeouts(opts) {
|
|
119
|
-
const timeout = opts.resourceTimeout;
|
|
120
|
-
const globalWarn = opts.resourceWarnAfter?.globalMs;
|
|
121
|
-
const globalTimeout = timeout?.globalMs;
|
|
122
|
-
if (typeof globalWarn === "number" && typeof globalTimeout === "number") {
|
|
123
|
-
if (globalWarn >= globalTimeout) throw new Error(`--resource-warn-after (${globalWarn}ms) must be less than --resource-timeout (${globalTimeout}ms)`);
|
|
124
|
-
} else if (typeof globalTimeout === "number") {
|
|
125
|
-
if (3e5 >= globalTimeout) {
|
|
126
|
-
const lowered = autoLoweredWarnMs(globalTimeout);
|
|
127
|
-
ensureWarnAfter(opts).globalMs = lowered;
|
|
128
|
-
getLogger().warn(`--resource-warn-after defaulted to ${formatMs(lowered)} because --resource-timeout ${formatMs(globalTimeout)} is shorter than the ${formatMs(DEFAULT_RESOURCE_WARN_AFTER_MS)} default. Pass --resource-warn-after ${commandHole("duration")} explicitly to override.`);
|
|
129
|
-
}
|
|
130
|
-
} else if (typeof globalWarn === "number" && globalWarn >= 18e5) throw new Error(`--resource-warn-after (${formatMs(globalWarn)}) must be less than --resource-timeout (default ${formatMs(DEFAULT_RESOURCE_TIMEOUT_MS)}). Pass --resource-timeout ${commandHole("duration")} alongside it to raise the deadline.`);
|
|
131
|
-
const warnPerType = opts.resourceWarnAfter?.perTypeMs ?? {};
|
|
132
|
-
const timeoutPerType = timeout?.perTypeMs ?? {};
|
|
133
|
-
const types = /* @__PURE__ */ new Set([...Object.keys(warnPerType), ...Object.keys(timeoutPerType)]);
|
|
134
|
-
for (const t of types) {
|
|
135
|
-
const explicitPerTypeWarn = warnPerType[t];
|
|
136
|
-
const explicitPerTypeTimeout = timeoutPerType[t];
|
|
137
|
-
const effectiveGlobalWarn = opts.resourceWarnAfter?.globalMs;
|
|
138
|
-
const effectiveWarn = explicitPerTypeWarn ?? effectiveGlobalWarn ?? 3e5;
|
|
139
|
-
const effectiveTimeout = explicitPerTypeTimeout ?? globalTimeout ?? 18e5;
|
|
140
|
-
if (effectiveWarn < effectiveTimeout) continue;
|
|
141
|
-
if (explicitPerTypeWarn !== void 0 && explicitPerTypeTimeout !== void 0) throw new Error(`--resource-warn-after for ${t} (${formatMs(explicitPerTypeWarn)}) must be less than --resource-timeout for ${t} (${formatMs(explicitPerTypeTimeout)})`);
|
|
142
|
-
if (explicitPerTypeWarn !== void 0) throw new Error(`--resource-warn-after for ${t} (${formatMs(explicitPerTypeWarn)}) must be less than --resource-timeout for ${t} (${formatMs(effectiveTimeout)}). Pass --resource-timeout ${t}=${commandHole("duration")} alongside it to raise the deadline.`);
|
|
143
|
-
const lowered = autoLoweredWarnMs(effectiveTimeout);
|
|
144
|
-
ensureWarnAfter(opts).perTypeMs[t] = lowered;
|
|
145
|
-
getLogger().warn(`--resource-warn-after for ${t} defaulted to ${formatMs(lowered)} because --resource-timeout for ${t} (${formatMs(effectiveTimeout)}) is shorter than the inherited ${formatMs(effectiveWarn)} warn. Pass --resource-warn-after ${t}=${commandHole("duration")} explicitly to override.`);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
function ensureWarnAfter(opts) {
|
|
149
|
-
if (!opts.resourceWarnAfter) opts.resourceWarnAfter = { perTypeMs: {} };
|
|
150
|
-
if (!opts.resourceWarnAfter.perTypeMs) opts.resourceWarnAfter.perTypeMs = {};
|
|
151
|
-
return opts.resourceWarnAfter;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
// src/cli/options/provisioning-route.ts
|
|
155
|
-
const RESOURCE_TYPE_FORMAT = /^[A-Z][A-Za-z0-9]+(::[A-Z][A-Za-z0-9]+)+$/;
|
|
156
|
-
function parseAllowUnsupportedTypesToken(value, previous) {
|
|
157
|
-
const parsed = value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
158
|
-
for (const token of parsed) if (!RESOURCE_TYPE_FORMAT.test(token)) throw new Error(`Invalid --allow-unsupported-types value "${token}": expected a CloudFormation resource type like AWS::Service::Type or Custom::Foo.`);
|
|
159
|
-
return [...previous ?? [], ...parsed];
|
|
160
|
-
}
|
|
161
|
-
const allowUnsupportedTypesOption = new Option("--allow-unsupported-types <types>", "Comma-separated resource types to attempt via Cloud Control even though cdkd reports them unsupported (AWS NON_PROVISIONABLE). Escape hatch — Cloud Control will likely still fail. Example: --allow-unsupported-types AWS::Foo::Bar,AWS::Baz::Qux").argParser(parseAllowUnsupportedTypesToken);
|
|
162
|
-
const RESOURCE_PROPERTY_FORMAT = /^[A-Z][A-Za-z0-9]+(::[A-Z][A-Za-z0-9]+)+:[A-Z][A-Za-z0-9]*$/;
|
|
163
|
-
function parseRouteEntries(value, previous, flag) {
|
|
164
|
-
const parsed = value.split(",").map((s) => s.trim()).filter(Boolean);
|
|
165
|
-
for (const token of parsed) {
|
|
166
|
-
if (!RESOURCE_PROPERTY_FORMAT.test(token)) throw new Error(`Invalid ${flag} value "${token}": expected <ResourceType>:<PropertyName> with PascalCase on both halves (e.g. AWS::ApiGatewayV2::Api:Body).`);
|
|
167
|
-
if (token.startsWith("Custom::")) throw new Error(`Invalid ${flag} value "${token}": Custom:: resources are routed through cfn-response and have no SDK-unwired properties at cdkd, so the flag would have no effect. Use --allow-unsupported-types for type-level escape hatches instead.`);
|
|
168
|
-
}
|
|
169
|
-
return [...previous ?? [], ...parsed];
|
|
170
|
-
}
|
|
171
|
-
function parsePreferSdkRouteToken(value, previous) {
|
|
172
|
-
return parseRouteEntries(value, previous, "--prefer-sdk-route");
|
|
173
|
-
}
|
|
174
|
-
let deprecatedAliasWarned = false;
|
|
175
|
-
function parseAllowUnsupportedPropertiesToken(value, previous) {
|
|
176
|
-
if (!deprecatedAliasWarned) {
|
|
177
|
-
deprecatedAliasWarned = true;
|
|
178
|
-
process.stderr.write("--allow-unsupported-properties is deprecated and will be removed in the first minor release after 2026-12-01; use --prefer-sdk-route, which takes the same <ResourceType>:<PropertyName> tokens and does the same thing. The old name reads as the opposite of its behaviour: it does not make the property reach AWS, it keeps the resource on the SDK provider and accepts that the value is NOT written.\n");
|
|
179
|
-
}
|
|
180
|
-
return parseRouteEntries(value, previous, "--allow-unsupported-properties");
|
|
181
|
-
}
|
|
182
|
-
const preferSdkRouteOption = new Option("--prefer-sdk-route <entries>", "Comma-separated <ResourceType>:<PropertyName> tokens to keep on the SDK provider instead of auto-routing the resource to Cloud Control. The named values are then NOT written to AWS — the deployed resource is missing the field. Ignored for a resource that routes to Cloud Control for another reason (a sibling unwired property, or a sticky cc-api state record), where the values are written after all. Example: --prefer-sdk-route AWS::ApiGatewayV2::Api:Body").argParser(parsePreferSdkRouteToken);
|
|
183
|
-
const allowUnsupportedPropertiesOption = new Option("--allow-unsupported-properties <entries>", "Deprecated alias for --prefer-sdk-route.").argParser(parseAllowUnsupportedPropertiesToken).hideHelp();
|
|
184
|
-
const LOGICAL_ID_FORMAT = /^[A-Za-z][A-Za-z0-9]{0,254}$/;
|
|
185
|
-
function parseRecreateViaCcApiToken(value, previous) {
|
|
186
|
-
const token = value.trim();
|
|
187
|
-
if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --recreate-via-cc-api value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --recreate-via-cc-api flag per resource — repeat the flag for additional targets.`);
|
|
188
|
-
return [...previous ?? [], token];
|
|
189
|
-
}
|
|
190
|
-
const recreateViaCcApiOption = new Option("--recreate-via-cc-api <logicalId>", "Destroy + recreate the named resource (by CloudFormation logical id) via Cloud Control API in this deploy, so a top-level CFn property the SDK provider does not write reaches AWS via CC. Repeatable — pass the flag once per resource. Per-resource opt-in (no bulk / no per-stack shortcut) so the destroy-and-recreate cost is acknowledged for each target. Stateful resource types (RDS, DynamoDB, S3, EFS, ...) refuse unless --force-stateful-recreation is ALSO passed (two-flag protection). Cannot be combined with --prefer-sdk-route on the same resource type and property. Refused, with no bypass, for a type Cloud Control cannot create (NON_PROVISIONABLE).").argParser(parseRecreateViaCcApiToken);
|
|
191
|
-
function parseRecreateViaSdkProviderToken(value, previous) {
|
|
192
|
-
const token = value.trim();
|
|
193
|
-
if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --recreate-via-sdk-provider value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --recreate-via-sdk-provider flag per resource — repeat the flag for additional targets.`);
|
|
194
|
-
return [...previous ?? [], token];
|
|
195
|
-
}
|
|
196
|
-
function parsePinCcApiToken(value, previous) {
|
|
197
|
-
const token = value.trim();
|
|
198
|
-
if (!LOGICAL_ID_FORMAT.test(token)) throw new Error(`Invalid --pin-cc-api value "${value}": expected a CloudFormation logical id (alphanumeric, starts with a letter, max 255 chars). One --pin-cc-api flag per resource — repeat the flag for additional targets.`);
|
|
199
|
-
return [...previous ?? [], token];
|
|
200
|
-
}
|
|
201
|
-
const pinCcApiOption = new Option("--pin-cc-api <logicalId>", "Keep the named resource (by CloudFormation logical id) on the Cloud Control route in this deploy, declining the automatic return to the SDK Provider that a type-level sdk-coverage exemption would otherwise apply to a resource recorded as provisionedBy: cc-api. Repeatable — pass the flag once per resource. Has no effect on a resource already on the SDK path, and does not override an exemption admitted because Cloud Control cannot manage the type.").argParser(parsePinCcApiToken);
|
|
202
|
-
const recreateViaSdkProviderOption = new Option("--recreate-via-sdk-provider <logicalId>", "Destroy + recreate the named resource (by CloudFormation logical id) via cdkd's SDK Provider in this deploy, so a resource currently sticky on provisionedBy: cc-api flips back to provisionedBy: sdk. Used after a release adds SDK coverage for a type the user originally needed CC for (e.g. Lambda LoggingConfig). Repeatable — pass the flag once per resource. Per-resource opt-in. Stateful resource types refuse unless --force-stateful-recreation is ALSO passed.").argParser(parseRecreateViaSdkProviderToken);
|
|
203
|
-
|
|
204
|
-
// src/cli/options/assume-role.ts
|
|
205
|
-
function parseAssumeRoleToken(raw, previous) {
|
|
206
|
-
const acc = previous ?? { perLambda: nullPrototypeRecord() };
|
|
207
|
-
if (!acc.perLambda) acc.perLambda = nullPrototypeRecord();
|
|
208
|
-
const shownRaw = quotedArgv(raw, 613);
|
|
209
|
-
const eqIndex = raw.trim().startsWith("arn:") ? -1 : raw.indexOf("=");
|
|
210
|
-
if (eqIndex === -1) {
|
|
211
|
-
const bare = raw.trim();
|
|
212
|
-
if (!isIamRoleArn(bare)) throw new Error(`Invalid --assume-role value ${shownRaw}: expected an IAM role ARN like arn:aws:iam::123456789012:role/MyRole, or LogicalId='<arn>'.`);
|
|
213
|
-
acc.globalArn = bare;
|
|
214
|
-
return acc;
|
|
215
|
-
}
|
|
216
|
-
const logicalId = raw.substring(0, eqIndex).trim();
|
|
217
|
-
const arn = raw.substring(eqIndex + 1).trim();
|
|
218
|
-
if (!/^[A-Za-z][A-Za-z0-9]*$/.test(logicalId)) throw new Error(`Invalid --assume-role value ${shownRaw}: left-hand side ${quotedArgv(logicalId)} must be a CloudFormation logical ID (alphanumeric, leading letter).`);
|
|
219
|
-
if (!isIamRoleArn(arn)) throw new Error(`Invalid --assume-role value ${shownRaw}: right-hand side ${quotedArgv(arn, 613)} must be an IAM role ARN like arn:aws:iam::123456789012:role/MyRole.`);
|
|
220
|
-
acc.perLambda[logicalId] = arn;
|
|
221
|
-
return acc;
|
|
222
|
-
}
|
|
223
|
-
function quotedArgv(value, maxCodePoints) {
|
|
224
|
-
const shown = displayIdent(value, maxCodePoints === void 0 ? void 0 : { maxCodePoints });
|
|
225
|
-
return !/\s/.test(value) && shown === value ? `"${value}"` : shellBoundedDisplay(shown);
|
|
226
|
-
}
|
|
227
|
-
function normalizeStartApiAssumeRole(raw, autoResolve) {
|
|
228
|
-
if (raw === void 0) return autoResolve ? {
|
|
229
|
-
perLambda: nullPrototypeRecord(),
|
|
230
|
-
bareAutoResolve: true
|
|
231
|
-
} : void 0;
|
|
232
|
-
if (autoResolve && raw.globalArn) throw new Error(`--assume-role-auto auto-resolves EACH routed Lambda's own execution role, but --assume-role ${quotedArgv(raw.globalArn, 613)} also names a single global default. These are mutually exclusive on the global slot. Either drop the global ARN to keep --assume-role-auto for every Lambda, or drop --assume-role-auto to keep the global default. Per-Lambda overrides (--assume-role '<LogicalId>'='<arn>') are compatible with either side.`);
|
|
233
|
-
if (autoResolve) raw.bareAutoResolve = true;
|
|
234
|
-
return raw;
|
|
235
|
-
}
|
|
236
|
-
function effectiveAssumeRoleArn(logicalId, opt) {
|
|
237
|
-
if (!opt) return void 0;
|
|
238
|
-
const perLambda = opt.perLambda;
|
|
239
|
-
if (perLambda && Object.hasOwn(perLambda, logicalId)) return perLambda[logicalId];
|
|
240
|
-
return opt.globalArn;
|
|
241
|
-
}
|
|
242
|
-
|
|
243
|
-
// src/cli/options.ts
|
|
244
|
-
function parseContextOptions(contextArgs) {
|
|
245
|
-
const context = nullPrototypeRecord();
|
|
246
|
-
if (contextArgs) for (const arg of contextArgs) {
|
|
247
|
-
const eqIndex = arg.indexOf("=");
|
|
248
|
-
if (eqIndex > 0) context[arg.substring(0, eqIndex)] = arg.substring(eqIndex + 1);
|
|
249
|
-
}
|
|
250
|
-
return context;
|
|
251
|
-
}
|
|
252
|
-
const commonOptions = [
|
|
253
|
-
new Option("--verbose", "Enable verbose logging").default(false),
|
|
254
|
-
new Option("--profile <profile>", "AWS profile"),
|
|
255
|
-
new Option("--role-arn <arn>", "IAM role ARN to assume for AWS API calls (env: CDKD_ROLE_ARN); the role needs the actions for the resource types you deploy plus the bookkeeping actions cdkd itself issues, because cdkd makes raw service API calls and does not route through CloudFormation, so CDK CLI deploy-roles will NOT work. Combines with --profile: the profile supplies the base credentials the role is assumed FROM, and the role is what every later AWS call runs as"),
|
|
256
|
-
new Option("-y, --yes", "Automatically answer interactive prompts with the recommended response (e.g. confirm destroy)").default(false)
|
|
257
|
-
];
|
|
258
|
-
const deprecatedRegionOption = new Option("--region <region>", "[deprecated] Prefer AWS_REGION or your AWS profile; --region is still honored but will be removed in a future release").hideHelp();
|
|
259
|
-
function warnIfDeprecatedRegion(options) {
|
|
260
|
-
if (options.region !== void 0) process.stderr.write("Warning: --region is deprecated and will be removed in a future release. It is still honored for now (it overrides AWS_REGION / your AWS profile), but prefer the AWS_REGION environment variable or your AWS profile to choose the region.\n");
|
|
261
|
-
}
|
|
262
|
-
const appOptions = [new Option("-a, --app <command>", "CDK app command (e.g., \"node app.ts\") or path to a pre-synthesized cloud assembly directory. Falls back to cdk.json or CDKD_APP env"), new Option("--output <path>", "Output directory for synthesis").default("cdk.out")];
|
|
263
|
-
const stateOptions = [new Option("--state-bucket <bucket>", "S3 bucket for state storage. Falls back to CDKD_STATE_BUCKET env or cdk.json"), new Option("--state-prefix <prefix>", "S3 key prefix for state files").default(DEFAULT_STATE_PREFIX).argParser(parseStatePrefix)];
|
|
264
|
-
function parseStatePrefix(value) {
|
|
265
|
-
if (value.includes("<") || value.includes(">")) throw new InvalidArgumentError("a state prefix cannot contain '<' or '>': that is a placeholder cdkd printed in a suggested command for a value it could not show. Replace it with your actual prefix.");
|
|
266
|
-
return value;
|
|
267
|
-
}
|
|
268
|
-
const stackOptions = [new Option("--stack <name>", "Stack name to operate on")];
|
|
269
|
-
function parseStackRegion(value) {
|
|
270
|
-
if (value.trim() === "") throw new InvalidArgumentError(`expected a region name (e.g. us-east-1), got ${value === "" ? "an empty value" : "whitespace only"}. Omit the flag entirely to operate on every region a stack has state in.`);
|
|
271
|
-
return value;
|
|
272
|
-
}
|
|
273
|
-
function guardStackRegionOptions(cmd) {
|
|
274
|
-
for (const option of cmd.options) if (option.long === "--stack-region" && option.parseArg === void 0) option.argParser(parseStackRegion);
|
|
275
|
-
for (const sub of cmd.commands) guardStackRegionOptions(sub);
|
|
276
|
-
}
|
|
277
|
-
const noWaitOption = new Option("--no-wait", "Skip waiting for async resources to stabilize (RDS, ElastiCache, NAT Gateway, EC2 Instance, ELBv2 LoadBalancer, Lambda MicroVM Image, ECS Service steady state)");
|
|
278
|
-
const fullWaitOption = new Option("--full-wait", "Also wait for stabilizations cdkd skips by default, matching CloudFormation (CloudFront Distribution Deployed, RDS Multi-AZ DB cluster storage optimization; raise --resource-timeout AWS::RDS::DBCluster for a long one)");
|
|
279
|
-
function validateWaitFlags(opts) {
|
|
280
|
-
if (opts.wait === false && opts.fullWait === true) throw new Error("--no-wait and --full-wait cannot be combined: --no-wait skips stabilization waits, --full-wait adds them. Pick one.");
|
|
281
|
-
}
|
|
282
|
-
function applyWaitFlagEnv(opts) {
|
|
283
|
-
validateWaitFlags(opts);
|
|
284
|
-
process.env["CDKD_WAIT_FLAGS_AVAILABLE"] = "true";
|
|
285
|
-
if (opts.wait === false) process.env["CDKD_NO_WAIT"] = "true";
|
|
286
|
-
if (opts.fullWait === true) process.env["CDKD_FULL_WAIT"] = "true";
|
|
287
|
-
}
|
|
288
|
-
const aggressiveVpcParallelOption = new Option("--no-aggressive-vpc-parallel", "Disable the default relaxation of CDK-injected VPC route DependsOn (on by default; opt out to keep the strict CDK ordering)");
|
|
289
|
-
const forceStatefulRecreationOption = new Option("--force-stateful-recreation", "Confirm a data-losing destroy + recreate of a stateful resource. Required whenever a replacement target is a stateful type on the --recreate-via-cc-api / --recreate-via-sdk-provider pre-flight, with --replace, AND on the paths a plain deploy reaches with no flag: a template immutable-property change, and an in-place update the provisioning layer rejects. Stateful types are databases, filesystems, KMS keys, table / vector storage, source repositories, and more; https://cdkd.dev/cli-deploy-safety/ carries the full list. S3 buckets and log groups are the conditional cases: at pre-flight, a non-empty bucket, or a log group with retention, with log streams, or whose emptiness the probe could not settle; mid-deploy, ANY bucket or log group, because the emptiness probe cannot run there. The two probes differ on failure — the bucket fails open, the log group closed. Destroy + recreate loses ALL data in the resource — no automatic data migration. Full opt-in for CI use: --recreate-via-cc-api '<id>' --force-stateful-recreation --yes.").default(false);
|
|
290
|
-
const replaceOption = new Option("--replace", "Replace (DELETE + CREATE) a resource whose in-place update is rejected because an immutable property changed and AWS exposes no update API for it (e.g. Lambda LayerVersion content, EFS AccessPoint, ECS TaskDefinition, ApiGatewayV2 immutable fields). Without this flag such a change fails the deploy. Stateful types (RDS / DynamoDB / EFS / any S3 bucket / any Logs log group / etc.) ALSO require --force-stateful-recreation since the replacement is a data-losing DELETE + CREATE — mid-deploy neither emptiness probe can run, so both conditional types count as stateful there.").default(false);
|
|
291
|
-
const useCdkBootstrapAssetsOption = new Option("--use-cdk-bootstrap-assets", "Publish assets to the CDK bootstrap bucket/repo named by the asset manifest verbatim, skipping the cdkd asset-storage redirection even when this region is opted in via 'cdkd bootstrap'. For apps deployed via both CloudFormation and cdkd during a migration window. Per-app pin: cdk.json context.cdkd.useCdkBootstrapAssets. Also suppresses the legacy-mode 'cdk gc' notice.").default(false);
|
|
292
|
-
const strictGetattOption = new Option("--strict-getatt", "Fail the deploy on ANY Fn::GetAtt that falls back to the physical ID because cdkd cannot construct the attribute (default: warn and use the physical ID, hard-failing only when the fallback is knowably wrong — an *Arn attribute with a non-ARN value or a *Url attribute with a non-http(s) value). Also fails the deploy when a stack Output cannot be resolved (default: warn and store no value).").default(false);
|
|
293
|
-
const allowUnaddressedOption = new Option("--allow-unaddressed", "Exit 0 even when the deploy left a resource unaddressed — a DELETE the provider could not issue, or a replacement whose old resource survives untracked (default: exit 2, matching cdkd destroy). The summary rows and warnings are printed either way; only the exit code changes.").default(false);
|
|
294
|
-
const noCfnFallbackOption = new Option("--no-cfn-fallback", "Do not fall back to CloudFormation (ListExports / stack outputs) when an Fn::ImportValue / Fn::GetStackOutput reference is not found in cdkd state (default: fall back, so producers still managed by CloudFormation can be referenced)");
|
|
295
|
-
const annotationMessageOptions = [new Option("--strict", "Do not proceed with stacks carrying warning annotations").default(false), new Option("--ignore-errors", "Ignore error annotations from stack synthesis, which will likely produce an invalid deployment").default(false)];
|
|
296
|
-
function exclusivelyOption(command) {
|
|
297
|
-
return new Option("-e, --exclusively", command === "deploy" ? "Only deploy requested stacks, do not include dependencies" : "Only destroy requested stacks, do not include the stacks that depend on them").default(false);
|
|
298
|
-
}
|
|
299
|
-
const deployOptions = [
|
|
300
|
-
new Option("--concurrency <number>", "Maximum concurrent resource operations").default(20).argParser((value) => parseInt(value, 10)),
|
|
301
|
-
new Option("--stack-concurrency <number>", "Maximum concurrent stack deployments").default(4).argParser((value) => parseInt(value, 10)),
|
|
302
|
-
new Option("--asset-publish-concurrency <number>", "Maximum concurrent asset publish operations (S3 uploads + ECR push)").default(8).argParser((value) => parseInt(value, 10)),
|
|
303
|
-
new Option("--image-build-concurrency <number>", "Maximum concurrent Docker image builds").default(4).argParser((value) => parseInt(value, 10)),
|
|
304
|
-
new Option("--dry-run", "Show changes without applying").default(false),
|
|
305
|
-
new Option("--skip-assets", "Skip asset publishing").default(false),
|
|
306
|
-
new Option("--no-rollback", "Skip rollback on deployment failure"),
|
|
307
|
-
new Option("--no-auto-asset-storage", "Do not auto-create cdkd-owned asset storage (asset bucket + container-asset ECR repo + marker) on the first deploy into a region not yet opted in via 'cdkd bootstrap'. Deploys into such regions stay in legacy mode (CDK bootstrap destinations). Per-app opt-out: cdk.json context.cdkd.autoAssetStorage: false."),
|
|
308
|
-
new Option("--no-capture-observed-state", "Skip capturing AWS-current properties after each create/update (adds a fire-and-forget readCurrentState per resource so cdkd drift can compare against the real deploy-time AWS snapshot instead of the template). On by default. Disable when deploy speed matters more than rich drift detection — falls back to comparing against template properties (the pre-v3 behavior)."),
|
|
309
|
-
new Option("--prefix-user-supplied-names", "Opt in to LEGACY behavior: prepend the stack name to physical names the user explicitly supplied in their CDK code (e.g. `new iam.Role(this, \"X\", { roleName: \"my-role\" })` → AWS resource named `MyStack-my-role` instead of `my-role`). Since v0.94.0 the default is to NOT prefix user-supplied names — this flag restores the pre-v0.94.0 behavior on Pattern B providers (IAM Role / User / Group / InstanceProfile / ManagedPolicy / ELBv2 LoadBalancer / TargetGroup). Enable via this flag, CDKD_PREFIX_USER_SUPPLIED_NAMES=true, or cdk.json context.cdkd.prefixUserSuppliedNames=true. Applies to `cdkd deploy` only.").default(false),
|
|
310
|
-
noWaitOption,
|
|
311
|
-
fullWaitOption,
|
|
312
|
-
aggressiveVpcParallelOption,
|
|
313
|
-
exclusivelyOption("deploy"),
|
|
314
|
-
allowUnsupportedTypesOption,
|
|
315
|
-
preferSdkRouteOption,
|
|
316
|
-
allowUnsupportedPropertiesOption,
|
|
317
|
-
recreateViaCcApiOption,
|
|
318
|
-
recreateViaSdkProviderOption,
|
|
319
|
-
pinCcApiOption,
|
|
320
|
-
forceStatefulRecreationOption,
|
|
321
|
-
replaceOption,
|
|
322
|
-
useCdkBootstrapAssetsOption,
|
|
323
|
-
strictGetattOption,
|
|
324
|
-
noCfnFallbackOption,
|
|
325
|
-
allowUnaddressedOption,
|
|
326
|
-
...resourceTimeoutOptions
|
|
327
|
-
];
|
|
328
|
-
const contextOptions = [new Option("-c, --context <key=value...>", "Set context values (can be specified multiple times)")];
|
|
329
|
-
const destroyOptions = [
|
|
330
|
-
new Option("-f, --force", "Do not ask for confirmation before destroying the stacks").default(false),
|
|
331
|
-
new Option("--remove-protection", `Bypass deletion protection on protected resources by flipping the per-resource protection flag off in-place before delete. Covers stack-level terminationProtection (CDK property) and resource-level protection on ${removeProtectionTypeList()}.`).default(false),
|
|
332
|
-
allowUnsupportedTypesOption
|
|
333
|
-
];
|
|
334
|
-
const skipFinalSnapshotOption = new Option("--skip-final-snapshot", "Delete resources whose DeletionPolicy (or, on replacements, UpdateReplacePolicy) is 'Snapshot' — including an RDS DB cluster or standalone DB instance with no DeletionPolicy, whose CloudFormation default is 'Snapshot' — WITHOUT creating the final snapshot the policy promises (DATA LOSS — explicit opt-out of CloudFormation parity). By default cdkd creates the final snapshot for every CloudFormation-supported type (RDS DBInstance / DBCluster, Neptune / DocDB clusters, ElastiCache CacheCluster / ReplicationGroup, Redshift Cluster, EC2 Volume) and refuses the delete when it cannot — e.g. a resource managed via the Cloud Control API route, whose delete has no final-snapshot parameter. On 'cdkd rollback' the flag governs the rolled-back CREATE's DeletionPolicy; a reverse-replacement delete of the NEW resource keeps its own bounded UpdateReplacePolicy behavior and is unaffected.").default(false);
|
|
335
|
-
|
|
336
|
-
// src/local/local-role-arn.ts
|
|
337
|
-
async function applyRoleArnForLocal(opts) {
|
|
338
|
-
if (getActiveWorkloadAwsWiring()?.mixed) await runWithRealAws(() => applyRoleArnIfSet(opts));
|
|
339
|
-
else await applyRoleArnIfSet(opts);
|
|
340
|
-
const role = getAssumedRoleCredentials();
|
|
341
|
-
if (role === void 0) return;
|
|
342
|
-
recordAssumedRole(getPreAssumeEnvCredentials(), {
|
|
343
|
-
accessKeyId: role.accessKeyId,
|
|
344
|
-
secretAccessKey: role.secretAccessKey,
|
|
345
|
-
sessionToken: role.sessionToken
|
|
346
|
-
});
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
// src/cli/commands/local-profile-credentials-file.ts
|
|
350
|
-
const CONTAINER_AWS_CREDENTIALS_PATH = "/cdkd-aws/credentials";
|
|
351
|
-
async function writeProfileCredentialsFile(profileName, creds, opts) {
|
|
352
|
-
if (profileName === "") throw new Error("writeProfileCredentialsFile: profile name must not be empty.");
|
|
353
|
-
if (/[\r\n[\]]/.test(profileName)) throw new Error(`writeProfileCredentialsFile: profile name ${displayIdent(profileName)} contains a forbidden character (any of CR, LF, '[', ']' would corrupt the INI file or the docker -e env var).`);
|
|
354
|
-
const dir = await mkdtemp(path.join(tmpdir(), "cdkd-profile-creds-"));
|
|
355
|
-
const hostPath = path.join(dir, "credentials");
|
|
356
|
-
opts?.onDirCreated?.(hostPath);
|
|
357
|
-
const lines = [
|
|
358
|
-
`[${profileName}]`,
|
|
359
|
-
`aws_access_key_id = ${creds.accessKeyId}`,
|
|
360
|
-
`aws_secret_access_key = ${creds.secretAccessKey}`
|
|
361
|
-
];
|
|
362
|
-
if (creds.sessionToken) lines.push(`aws_session_token = ${creds.sessionToken}`);
|
|
363
|
-
try {
|
|
364
|
-
await writeFile(hostPath, lines.join("\n") + "\n", { mode: 384 });
|
|
365
|
-
} catch (err) {
|
|
366
|
-
let removed = true;
|
|
367
|
-
await rm(dir, {
|
|
368
|
-
recursive: true,
|
|
369
|
-
force: true
|
|
370
|
-
}).catch(() => {
|
|
371
|
-
removed = false;
|
|
372
|
-
});
|
|
373
|
-
if (removed) try {
|
|
374
|
-
opts?.onDirRemoved?.(hostPath);
|
|
375
|
-
} catch {}
|
|
376
|
-
throw err;
|
|
377
|
-
}
|
|
378
|
-
return {
|
|
379
|
-
hostPath,
|
|
380
|
-
containerPath: CONTAINER_AWS_CREDENTIALS_PATH,
|
|
381
|
-
profileName,
|
|
382
|
-
dispose: async () => {
|
|
383
|
-
await rm(dir, {
|
|
384
|
-
recursive: true,
|
|
385
|
-
force: true
|
|
386
|
-
});
|
|
387
|
-
}
|
|
388
|
-
};
|
|
389
|
-
}
|
|
390
|
-
function strandedProfileCredentialsNotice(hostPath) {
|
|
391
|
-
if (hostPath === void 0) return void 0;
|
|
392
|
-
return `The AWS credentials file mounted into the containers is NOT removed: delete ${displayIdent(hostPath)} once you tear them down.`;
|
|
393
|
-
}
|
|
394
|
-
|
|
395
|
-
// src/local/local-aws-wiring.ts
|
|
396
|
-
async function activateLocalAwsWiring(options) {
|
|
397
|
-
assertAwsEmulatorValue(options.awsEmulator);
|
|
398
|
-
try {
|
|
399
|
-
await activateWorkloadAwsWiring({
|
|
400
|
-
awsEmulator: options.awsEmulator,
|
|
401
|
-
caBundle: options.caBundle,
|
|
402
|
-
profile: options.profile,
|
|
403
|
-
pull: options.pull,
|
|
404
|
-
envVars: options.envVars
|
|
405
|
-
});
|
|
406
|
-
} catch (err) {
|
|
407
|
-
const cause = err instanceof Error && err.cause instanceof Error ? err.cause : void 0;
|
|
408
|
-
throw new CdkdError(err instanceof Error ? err.message : String(err), "LOCAL_AWS_WIRING_FAILED", cause);
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
async function activateLocalAwsAndRoleArn(options) {
|
|
412
|
-
await activateLocalAwsWiring(options);
|
|
413
|
-
await applyRoleArnForLocal({
|
|
414
|
-
roleArn: options.roleArn,
|
|
415
|
-
region: options.region
|
|
416
|
-
});
|
|
417
|
-
}
|
|
418
|
-
function assertAwsEmulatorValue(flag) {
|
|
419
|
-
const value = resolveAwsEmulatorOption(flag);
|
|
420
|
-
if (typeof value !== "string") return;
|
|
421
|
-
const where = `--aws-emulator (or ${awsEmulatorEnvName()})`;
|
|
422
|
-
let u;
|
|
423
|
-
try {
|
|
424
|
-
u = new URL(value);
|
|
425
|
-
} catch {
|
|
426
|
-
u = void 0;
|
|
427
|
-
}
|
|
428
|
-
if (u === void 0 ? /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*@/i.test(value) || /[?#]/.test(value) : u.username !== "" || u.password !== "" || u.search !== "" || u.hash !== "") throw new CdkdError(`${where} must be a bare scheme://host:port URL; the value carries a user name, password, query or fragment, which is not shown here. Remove it.`, "LOCAL_AWS_WIRING_FAILED");
|
|
429
|
-
if (u === void 0 || u.protocol !== "https:" && u.protocol !== "http:") throw new CdkdError(`${where} takes an http(s) URL such as https://127.0.0.1:9297, and the value given is not one. The URL is OPTIONAL, so a value right after the flag is taken as the URL: put --aws-emulator after the target, or write --aws-emulator=<url>.`, "LOCAL_AWS_WIRING_FAILED");
|
|
430
|
-
}
|
|
431
|
-
async function applyLocalAwsWiring(wiring, env, extraMounts, takenContainerPaths) {
|
|
432
|
-
const defaults = wiring.mode === "forward" && !env["AWS_ACCESS_KEY_ID"] ? await resolveHostDefaultCredentials() : void 0;
|
|
433
|
-
const wiredEnv = applyWorkloadAwsWiringToEnv(env, wiring, defaults);
|
|
434
|
-
const emulatorOnly = workloadGetsEmulatorKeysOnly(env, wiring);
|
|
435
|
-
const mounts = extraMounts.filter((m) => !emulatorOnly || m.containerPath !== "/cdkd-aws/credentials");
|
|
436
|
-
const taken = /* @__PURE__ */ new Set([...takenContainerPaths, ...mounts.map((m) => m.containerPath)]);
|
|
437
|
-
for (const m of wiring.mounts) if (!taken.has(m.containerPath)) mounts.push({
|
|
438
|
-
...m,
|
|
439
|
-
readOnly: true
|
|
440
|
-
});
|
|
441
|
-
return {
|
|
442
|
-
env: wiredEnv,
|
|
443
|
-
extraMounts: mounts
|
|
444
|
-
};
|
|
445
|
-
}
|
|
446
|
-
function loopbackPortsFor(wiring, env, network) {
|
|
447
|
-
if (network !== "host") return effectiveLoopbackPorts(env, wiring);
|
|
448
|
-
const mixed = wiring.mixed;
|
|
449
|
-
if (mixed && effectiveLoopbackPorts(env, wiring).includes(mixed.resignPort)) throw new CdkdError("A run with \"real-aws\" exceptions (AWS Emulator mixed mode) cannot use the host network: its re-signing sidecar listens on the workload's own loopback. Drop the \"real-aws\" exceptions or the host network.", "LOCAL_AWS_EMULATOR_FORWARDER_FAILED");
|
|
450
|
-
return [];
|
|
451
|
-
}
|
|
452
|
-
async function prepareLocalLoopbackForwarder(wiring) {
|
|
453
|
-
try {
|
|
454
|
-
await ensureForwarderImage(wiring.skipPull === true);
|
|
455
|
-
} catch (err) {
|
|
456
|
-
if (wiring.mode === "emulator" || wiring.mixed) throw new CdkdError(`--aws-emulator: the loopback forwarder image could not be pulled: ${err.message}`, "LOCAL_AWS_EMULATOR_FORWARDER_PULL_FAILED");
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
async function attachLocalLoopbackForwarder(containerId, ports) {
|
|
460
|
-
const wiring = getActiveWorkloadAwsWiring$1();
|
|
461
|
-
if (!wiring) return;
|
|
462
|
-
try {
|
|
463
|
-
await (ports === void 0 ? attachLoopbackForwarder(containerId, wiring) : attachLoopbackForwarder(containerId, wiring, ports));
|
|
464
|
-
} catch (err) {
|
|
465
|
-
throw new CdkdError(err instanceof Error ? err.message : String(err), "LOCAL_AWS_EMULATOR_FORWARDER_FAILED", err instanceof Error ? err : void 0);
|
|
466
|
-
}
|
|
467
|
-
}
|
|
468
|
-
async function profileCredentialsForWorkload(profile, resolve) {
|
|
469
|
-
if (!profile || localAwsEmulatorActive()) return void 0;
|
|
470
|
-
return resolve(profile);
|
|
471
|
-
}
|
|
472
|
-
function setContainerRegion(env, region) {
|
|
473
|
-
if (!region) return;
|
|
474
|
-
const folded = canonicalizeRegion(region);
|
|
475
|
-
env["AWS_REGION"] = folded;
|
|
476
|
-
env["AWS_DEFAULT_REGION"] = folded;
|
|
477
|
-
}
|
|
478
|
-
function localAwsEmulatorActive() {
|
|
479
|
-
return getActiveWorkloadAwsWiring$1()?.mode === "emulator";
|
|
480
|
-
}
|
|
481
|
-
function localAwsEmulatorCredentials() {
|
|
482
|
-
const wiring = getActiveWorkloadAwsWiring$1();
|
|
483
|
-
return wiring?.mode === "emulator" ? wiring.emulatorCredentials : void 0;
|
|
484
|
-
}
|
|
485
|
-
function workloadGetsEmulatorKeysOnly(env, wiring) {
|
|
486
|
-
if (!wiring) return false;
|
|
487
|
-
if (wiring.mode === "emulator") return true;
|
|
488
|
-
if (!wiring.mixed) return false;
|
|
489
|
-
return !Object.entries(env).some(([k, v]) => k !== "AWS_ENDPOINT_URL" && isRealAwsSentinel(k, v));
|
|
490
|
-
}
|
|
491
|
-
function mixedModeActive() {
|
|
492
|
-
return getActiveWorkloadAwsWiring$1()?.mixed !== void 0;
|
|
493
|
-
}
|
|
494
|
-
function realAwsException(service, workload) {
|
|
495
|
-
return mixedModeActive() && !isAwsServiceRoutedToEmulator(service, workload);
|
|
496
|
-
}
|
|
497
|
-
function mixedModeEmulatorOverride() {
|
|
498
|
-
return getAwsEndpointOverride() ?? getActiveWorkloadAwsWiring$1()?.mixed?.emulatorClientOverride;
|
|
499
|
-
}
|
|
500
|
-
function warnAwsEmulatorStateSourceHint(dropped, stateSourceGiven) {
|
|
501
|
-
if (dropped === 0 || stateSourceGiven) return;
|
|
502
|
-
const hint = takeAwsEmulatorStateSourceHint();
|
|
503
|
-
if (hint !== void 0) getLogger().warn(hint);
|
|
504
|
-
}
|
|
505
|
-
|
|
506
46
|
// src/cli/aws-emulator-activation.ts
|
|
507
47
|
async function activateAwsEmulatorForCommand(flag) {
|
|
508
48
|
try {
|
|
@@ -685,231 +225,6 @@ function defaultProfileRegion(ini) {
|
|
|
685
225
|
}
|
|
686
226
|
}
|
|
687
227
|
|
|
688
|
-
// src/cli/region-options.ts
|
|
689
|
-
function foldRegionOption(options) {
|
|
690
|
-
if (options.region !== void 0) options.region = canonicalizeRegion(options.region);
|
|
691
|
-
for (const key of ["AWS_REGION", "AWS_DEFAULT_REGION"]) {
|
|
692
|
-
const value = process.env[key];
|
|
693
|
-
if (value) process.env[key] = canonicalizeRegion(value);
|
|
694
|
-
}
|
|
695
|
-
}
|
|
696
|
-
function namedCliRegion(optionRegion) {
|
|
697
|
-
return canonicalizeRegion(optionRegion || process.env["AWS_REGION"]) || void 0;
|
|
698
|
-
}
|
|
699
|
-
function rawCliRegion(optionRegion) {
|
|
700
|
-
return optionRegion || process.env["AWS_REGION"] || void 0;
|
|
701
|
-
}
|
|
702
|
-
async function resolveEffectiveRegion(options) {
|
|
703
|
-
const flag = canonicalizeRegion(options.region);
|
|
704
|
-
if (flag) return {
|
|
705
|
-
region: flag,
|
|
706
|
-
source: "flag"
|
|
707
|
-
};
|
|
708
|
-
const awsRegion = canonicalizeRegion(process.env["AWS_REGION"]);
|
|
709
|
-
if (awsRegion && awsRegion === injectedAwsRegionValue()) return {
|
|
710
|
-
region: awsRegion,
|
|
711
|
-
source: "default-env"
|
|
712
|
-
};
|
|
713
|
-
if (awsRegion) return {
|
|
714
|
-
region: awsRegion,
|
|
715
|
-
source: "env"
|
|
716
|
-
};
|
|
717
|
-
const defaultRegionEnv = canonicalizeRegion(process.env["AWS_DEFAULT_REGION"]);
|
|
718
|
-
if (defaultRegionEnv) return {
|
|
719
|
-
region: defaultRegionEnv,
|
|
720
|
-
source: "default-env"
|
|
721
|
-
};
|
|
722
|
-
const fromProfile = canonicalizeRegion(await resolveSdkDefaultRegion(options.profile));
|
|
723
|
-
if (fromProfile) return {
|
|
724
|
-
region: fromProfile,
|
|
725
|
-
source: "profile"
|
|
726
|
-
};
|
|
727
|
-
return {
|
|
728
|
-
region: LEGACY_DEFAULT_REGION,
|
|
729
|
-
source: "default"
|
|
730
|
-
};
|
|
731
|
-
}
|
|
732
|
-
function exportInferredRegionForSdk(effective) {
|
|
733
|
-
if (effective.source !== "default-env") return;
|
|
734
|
-
injectAwsRegion(effective.region);
|
|
735
|
-
}
|
|
736
|
-
const LEGACY_DEFAULT_REGION = "us-east-1";
|
|
737
|
-
async function resolveSdkDefaultRegion(profile) {
|
|
738
|
-
const { STSClient } = await import("@aws-sdk/client-sts");
|
|
739
|
-
let client;
|
|
740
|
-
try {
|
|
741
|
-
client = new STSClient({
|
|
742
|
-
...awsClientDefaults({ profile }),
|
|
743
|
-
...profile && { profile }
|
|
744
|
-
});
|
|
745
|
-
return await client.config.region() || void 0;
|
|
746
|
-
} catch {
|
|
747
|
-
return;
|
|
748
|
-
} finally {
|
|
749
|
-
client?.destroy?.();
|
|
750
|
-
}
|
|
751
|
-
}
|
|
752
|
-
function ownedByLegacyDefault(probe) {
|
|
753
|
-
return { stateExists: (stackName, region) => probe.stateExistsOwnedBy(stackName, region, LEGACY_DEFAULT_REGION) };
|
|
754
|
-
}
|
|
755
|
-
async function placeStack(effective, stackName, probe) {
|
|
756
|
-
const [inResolved, inLegacy] = await Promise.all([probe.stateExists(stackName, effective.region), probe.stateExists(stackName, LEGACY_DEFAULT_REGION)]);
|
|
757
|
-
if (inResolved && inLegacy) return "both";
|
|
758
|
-
if (inResolved) return "resolved";
|
|
759
|
-
return inLegacy ? "legacy" : "none";
|
|
760
|
-
}
|
|
761
|
-
function bothRegionsMessage(effective, stackName) {
|
|
762
|
-
return `Stack ${quoteStackName(stackName)} has state in both ${LEGACY_DEFAULT_REGION} and ${displayIdent(effective.region)} (which ${inferredFrom(effective)} resolves). Continuing to use ${LEGACY_DEFAULT_REGION}, as a command with no region named did before. Set AWS_REGION=${displayIdent(effective.region)} to work on the ${displayIdent(effective.region)} one, or AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`;
|
|
763
|
-
}
|
|
764
|
-
function inferredFrom(effective) {
|
|
765
|
-
return effective.source === "default-env" ? "AWS_DEFAULT_REGION" : "your AWS profile";
|
|
766
|
-
}
|
|
767
|
-
function holdMessage(effective, stackName) {
|
|
768
|
-
return `Stack ${quoteStackName(stackName)} has existing state in ${LEGACY_DEFAULT_REGION}, but ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing stack is not duplicated. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message, or AWS_REGION=${displayIdent(effective.region)} to work in ${displayIdent(effective.region)} instead (where this stack has no state).`;
|
|
769
|
-
}
|
|
770
|
-
function quoteStackName(stackName) {
|
|
771
|
-
return displayIdent(stackName) === stackName ? `'${stackName}'` : "a stack whose name is not a plain identifier";
|
|
772
|
-
}
|
|
773
|
-
function stackRegionResolver(input) {
|
|
774
|
-
const { effective, logger } = input;
|
|
775
|
-
const probe = ownedByLegacyDefault(input.probe);
|
|
776
|
-
const placements = /* @__PURE__ */ new Map();
|
|
777
|
-
const place = (stackName) => {
|
|
778
|
-
let placement = placements.get(stackName);
|
|
779
|
-
if (placement === void 0) {
|
|
780
|
-
placement = placeStack(effective, stackName, probe);
|
|
781
|
-
placement.catch(() => placements.delete(stackName));
|
|
782
|
-
placements.set(stackName, placement);
|
|
783
|
-
}
|
|
784
|
-
return placement;
|
|
785
|
-
};
|
|
786
|
-
const answers = /* @__PURE__ */ new Map();
|
|
787
|
-
const answer = async (stackName) => {
|
|
788
|
-
const placement = await place(stackName);
|
|
789
|
-
if (placement === "legacy" || placement === "both") {
|
|
790
|
-
logger.info(placement === "both" ? bothRegionsMessage(effective, stackName) : holdMessage(effective, stackName));
|
|
791
|
-
return LEGACY_DEFAULT_REGION;
|
|
792
|
-
}
|
|
793
|
-
if (placement === "resolved") return effective.region;
|
|
794
|
-
const others = (input.siblings ?? []).filter((name) => name !== stackName);
|
|
795
|
-
const siblingPlacements = await Promise.all(others.map(place));
|
|
796
|
-
if (siblingPlacements.some((p) => p === "legacy" || p === "both") && !siblingPlacements.includes("resolved")) {
|
|
797
|
-
logger.info(`Stack ${quoteStackName(stackName)} has no state yet, and the other stacks of this app that have state all stay in ${LEGACY_DEFAULT_REGION}, while ${inferredFrom(effective)} resolves ${displayIdent(effective.region)}. Using ${LEGACY_DEFAULT_REGION} for it too, so the app stays in one region. Set AWS_REGION=${LEGACY_DEFAULT_REGION} to silence this message.`);
|
|
798
|
-
return LEGACY_DEFAULT_REGION;
|
|
799
|
-
}
|
|
800
|
-
return effective.region;
|
|
801
|
-
};
|
|
802
|
-
return (stackName, pinned) => {
|
|
803
|
-
if (pinned) return Promise.resolve(pinned);
|
|
804
|
-
if (!regionNeedsReconciliation(effective)) return Promise.resolve(effective.region);
|
|
805
|
-
let result = answers.get(stackName);
|
|
806
|
-
if (result === void 0) {
|
|
807
|
-
result = answer(stackName);
|
|
808
|
-
result.catch(() => answers.delete(stackName));
|
|
809
|
-
answers.set(stackName, result);
|
|
810
|
-
}
|
|
811
|
-
return result;
|
|
812
|
-
};
|
|
813
|
-
}
|
|
814
|
-
function stateWithRegion(state, region) {
|
|
815
|
-
return state.region ? state : {
|
|
816
|
-
...state,
|
|
817
|
-
region
|
|
818
|
-
};
|
|
819
|
-
}
|
|
820
|
-
function legacyStateBucketFallbackRegion(effective) {
|
|
821
|
-
return regionNeedsReconciliation(effective) ? LEGACY_DEFAULT_REGION : void 0;
|
|
822
|
-
}
|
|
823
|
-
async function reconcileExportIndexRegion(input) {
|
|
824
|
-
const { effective, probe, statePrefix, logger } = input;
|
|
825
|
-
if (!regionNeedsReconciliation(effective)) return effective.region;
|
|
826
|
-
const indexKey = (region) => `${statePrefix}/_index/${region}/exports.json`;
|
|
827
|
-
try {
|
|
828
|
-
if (!await probe.rawObjectExists(indexKey("us-east-1"))) return effective.region;
|
|
829
|
-
} catch (error) {
|
|
830
|
-
logger.warn(safeMsg`[region] could not probe the exports index (${error.name ?? "error"}); using ${effective.region}.`);
|
|
831
|
-
return effective.region;
|
|
832
|
-
}
|
|
833
|
-
logger.debug(safeMsg`[region] exports index exists in ${LEGACY_DEFAULT_REGION}; using it rather than ${effective.region} (inferred).`);
|
|
834
|
-
return LEGACY_DEFAULT_REGION;
|
|
835
|
-
}
|
|
836
|
-
function withOtherIndexRemoval(runStore, input) {
|
|
837
|
-
const { effective, runIndexRegion, statePrefix, probe, createStore, logger } = input;
|
|
838
|
-
const other = runIndexRegion === "us-east-1" ? effective.region : LEGACY_DEFAULT_REGION;
|
|
839
|
-
if (!regionNeedsReconciliation(effective) || other === runIndexRegion) return runStore;
|
|
840
|
-
let otherStore;
|
|
841
|
-
const removeFromOther = async (stackName, region) => {
|
|
842
|
-
try {
|
|
843
|
-
otherStore ??= probe.rawObjectExists(`${statePrefix}/_index/${other}/exports.json`).then((exists) => exists ? createStore(other) : void 0);
|
|
844
|
-
await (await otherStore)?.removeStackIfPresent(stackName, region);
|
|
845
|
-
} catch (error) {
|
|
846
|
-
otherStore = void 0;
|
|
847
|
-
logger.warn(safeMsg`Could not remove ${stackName}'s entries from the ${other} exports index (${error.name ?? "error"}); a later Fn::ImportValue may read a stale value from it.`);
|
|
848
|
-
}
|
|
849
|
-
};
|
|
850
|
-
return new Proxy(runStore, { get(target, prop, receiver) {
|
|
851
|
-
if (prop === "removeStack") return async (stackName, region) => {
|
|
852
|
-
await target.removeStack(stackName, region);
|
|
853
|
-
await removeFromOther(stackName, region);
|
|
854
|
-
};
|
|
855
|
-
const value = Reflect.get(target, prop, receiver);
|
|
856
|
-
return typeof value === "function" ? value.bind(target) : value;
|
|
857
|
-
} });
|
|
858
|
-
}
|
|
859
|
-
async function reconcileMarkerRegionWithLegacyDefault(input) {
|
|
860
|
-
const { effective, probe, markerKeyFor, logger } = input;
|
|
861
|
-
if (!regionNeedsReconciliation(effective)) return effective.region;
|
|
862
|
-
const markerExists = async (region) => {
|
|
863
|
-
try {
|
|
864
|
-
return await probe.getRawObject(markerKeyFor(region)) !== null;
|
|
865
|
-
} catch (error) {
|
|
866
|
-
if (error.name !== "NoSuchBucket") throw error;
|
|
867
|
-
logger.debug(`[region] no state bucket yet, so no bootstrap marker for ${region} (first bootstrap).`);
|
|
868
|
-
return false;
|
|
869
|
-
}
|
|
870
|
-
};
|
|
871
|
-
if (await markerExists(effective.region)) {
|
|
872
|
-
logger.debug(`[region] asset storage exists in ${effective.region} (from your AWS profile); using it.`);
|
|
873
|
-
return effective.region;
|
|
874
|
-
}
|
|
875
|
-
if (!await markerExists("us-east-1")) return effective.region;
|
|
876
|
-
logger.info(`cdkd asset storage exists in ${LEGACY_DEFAULT_REGION}, but your AWS profile resolves ${effective.region}. Continuing to use ${LEGACY_DEFAULT_REGION} so the existing storage is not orphaned. Pass '--region ${effective.region}' to target your profile's region, or '--region ${LEGACY_DEFAULT_REGION}' to silence this message.`);
|
|
877
|
-
return LEGACY_DEFAULT_REGION;
|
|
878
|
-
}
|
|
879
|
-
function regionNeedsReconciliation(effective) {
|
|
880
|
-
if (effective.source === "flag" || effective.source === "env") return false;
|
|
881
|
-
return effective.region !== LEGACY_DEFAULT_REGION;
|
|
882
|
-
}
|
|
883
|
-
function adoptDeprecatedRegionFlag(cmd) {
|
|
884
|
-
const registered = cmd.options;
|
|
885
|
-
const inherited = registered.findIndex((option) => option.long === "--region");
|
|
886
|
-
if (inherited !== -1) {
|
|
887
|
-
registered.splice(inherited, 1);
|
|
888
|
-
const emitter = cmd;
|
|
889
|
-
emitter.removeAllListeners("option:region");
|
|
890
|
-
emitter.removeAllListeners("optionEnv:region");
|
|
891
|
-
if (cmd.getOptionValueSource("region") === "default") {
|
|
892
|
-
const internals = cmd;
|
|
893
|
-
delete internals._optionValues["region"];
|
|
894
|
-
delete internals._optionValueSources["region"];
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
cmd.addOption(deprecatedRegionOption);
|
|
898
|
-
cmd.hook("preAction", (_thisCommand, actionCommand) => {
|
|
899
|
-
const options = actionCommand.opts();
|
|
900
|
-
warnIfDeprecatedRegion(options);
|
|
901
|
-
if (options.stackRegion !== void 0) {
|
|
902
|
-
options.rawStackRegion = options.stackRegion;
|
|
903
|
-
options.stackRegion = canonicalizeRegion(options.stackRegion);
|
|
904
|
-
}
|
|
905
|
-
foldRegionOption(options);
|
|
906
|
-
});
|
|
907
|
-
return cmd;
|
|
908
|
-
}
|
|
909
|
-
function regionShown(region) {
|
|
910
|
-
return displayIdent(region) === region ? plainOrDescribed(region, "region") : "a region that is not a plain identifier";
|
|
911
|
-
}
|
|
912
|
-
|
|
913
228
|
// src/cli/commands/bootstrap-destroy.ts
|
|
914
229
|
async function promptBootstrapDestroyConfirm(input) {
|
|
915
230
|
const logger = getLogger();
|
|
@@ -1217,6 +532,161 @@ async function bootstrapDestroyCommand(options) {
|
|
|
1217
532
|
}
|
|
1218
533
|
}
|
|
1219
534
|
|
|
535
|
+
// src/cli/commands/bootstrap-state-bucket.ts
|
|
536
|
+
async function createStateBucket(args) {
|
|
537
|
+
const { s3, bucketName, region, report } = args;
|
|
538
|
+
report(`Creating S3 bucket: ${bucketName} in region ${region}`);
|
|
539
|
+
const createBucketParams = { Bucket: bucketName };
|
|
540
|
+
if (region !== "us-east-1") createBucketParams.CreateBucketConfiguration = { LocationConstraint: region };
|
|
541
|
+
await s3.send(new CreateBucketCommand(createBucketParams));
|
|
542
|
+
report(`✓ Created S3 bucket: ${bucketName}`);
|
|
543
|
+
}
|
|
544
|
+
async function configureStateBucket(args) {
|
|
545
|
+
const { s3, bucketName, accountId, report } = args;
|
|
546
|
+
const logger = getLogger();
|
|
547
|
+
logger.debug("Enabling bucket versioning...");
|
|
548
|
+
await s3.send(new PutBucketVersioningCommand({
|
|
549
|
+
Bucket: bucketName,
|
|
550
|
+
ExpectedBucketOwner: accountId,
|
|
551
|
+
VersioningConfiguration: { Status: "Enabled" }
|
|
552
|
+
}));
|
|
553
|
+
report("✓ Enabled bucket versioning");
|
|
554
|
+
logger.debug("Enabling bucket encryption...");
|
|
555
|
+
await s3.send(new PutBucketEncryptionCommand({
|
|
556
|
+
Bucket: bucketName,
|
|
557
|
+
ExpectedBucketOwner: accountId,
|
|
558
|
+
ServerSideEncryptionConfiguration: { Rules: [{
|
|
559
|
+
ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" },
|
|
560
|
+
BucketKeyEnabled: true
|
|
561
|
+
}] }
|
|
562
|
+
}));
|
|
563
|
+
report("✓ Enabled bucket encryption (AES-256)");
|
|
564
|
+
logger.debug("Setting bucket policy...");
|
|
565
|
+
const bucketPolicy = buildDenyExternalAccessPolicy(bucketName, accountId, await s3.config.region());
|
|
566
|
+
await s3.send(new PutBucketPolicyCommand({
|
|
567
|
+
Bucket: bucketName,
|
|
568
|
+
ExpectedBucketOwner: accountId,
|
|
569
|
+
Policy: JSON.stringify(bucketPolicy)
|
|
570
|
+
}));
|
|
571
|
+
report("✓ Set bucket policy (deny external access)");
|
|
572
|
+
logger.debug("Setting custom-resource response lifecycle rule...");
|
|
573
|
+
const lifecycle = await applyCustomResourceResponseExpiration(s3, bucketName, { expectedBucketOwner: accountId });
|
|
574
|
+
if (lifecycle.status === "failed" || lifecycle.status === "refused") logger.warn(customResourceResponseExpirationWarning(bucketName, lifecycle));
|
|
575
|
+
else if (lifecycle.status === "added") report(safeMsg`✓ Set lifecycle rule (expire ${CUSTOM_RESOURCE_RESPONSE_PREFIX}/ responses after ${1} day)`);
|
|
576
|
+
else report(safeMsg`✓ Lifecycle rule ${CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID} already present (left unchanged)`);
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// src/cli/commands/bootstrap-noecho-mac-key.ts
|
|
580
|
+
function errorName(error) {
|
|
581
|
+
const raw = error?.name;
|
|
582
|
+
return typeof raw === "string" && /^[A-Za-z][A-Za-z0-9]{0,63}$/.test(raw) ? raw : "Error";
|
|
583
|
+
}
|
|
584
|
+
const NOECHO_MAC_KEY_ADMIN_ACTIONS = [
|
|
585
|
+
"kms:DescribeKey",
|
|
586
|
+
"kms:GetKeyPolicy",
|
|
587
|
+
"kms:PutKeyPolicy",
|
|
588
|
+
"kms:ListResourceTags",
|
|
589
|
+
"kms:ListGrants",
|
|
590
|
+
"kms:RevokeGrant",
|
|
591
|
+
"kms:CreateAlias",
|
|
592
|
+
"kms:UpdateAlias",
|
|
593
|
+
"kms:DeleteAlias",
|
|
594
|
+
"kms:EnableKey",
|
|
595
|
+
"kms:DisableKey",
|
|
596
|
+
"kms:UpdateKeyDescription",
|
|
597
|
+
"kms:TagResource",
|
|
598
|
+
"kms:UntagResource",
|
|
599
|
+
"kms:ScheduleKeyDeletion",
|
|
600
|
+
"kms:CancelKeyDeletion"
|
|
601
|
+
];
|
|
602
|
+
function noEchoMacKeyPolicy(partition, accountId) {
|
|
603
|
+
const root = { AWS: `arn:${partition}:iam::${accountId}:root` };
|
|
604
|
+
return JSON.stringify({
|
|
605
|
+
Version: "2012-10-17",
|
|
606
|
+
Statement: [{
|
|
607
|
+
Sid: "KeyAdministration",
|
|
608
|
+
Effect: "Allow",
|
|
609
|
+
Principal: root,
|
|
610
|
+
Action: [...NOECHO_MAC_KEY_ADMIN_ACTIONS],
|
|
611
|
+
Resource: "*"
|
|
612
|
+
}, {
|
|
613
|
+
Sid: "GenerateMacThroughIam",
|
|
614
|
+
Effect: "Allow",
|
|
615
|
+
Principal: root,
|
|
616
|
+
Action: "kms:GenerateMac",
|
|
617
|
+
Resource: "*"
|
|
618
|
+
}]
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
function partitionOfArn$1(arn) {
|
|
622
|
+
const partition = arn?.split(":")[1];
|
|
623
|
+
return partition !== void 0 && /^aws(-[a-z]+)*$/.test(partition) ? partition : "aws";
|
|
624
|
+
}
|
|
625
|
+
async function ensureNoEchoMacKey(args) {
|
|
626
|
+
const { kms, region, accountId, partition, report, warn } = args;
|
|
627
|
+
if (awsEndpointOverrideActive()) {
|
|
628
|
+
report(`Skipping the NoEcho value MAC key (${NOECHO_MAC_KEY_ALIAS}): AWS Emulator target`);
|
|
629
|
+
return "skipped";
|
|
630
|
+
}
|
|
631
|
+
const failed = (step, error) => {
|
|
632
|
+
warn(`Could not set up the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} in ${region} (${errorName(error)} from ${step}). Deploys keep working: a write-only property a NoEcho parameter feeds is re-sent on every deploy. Re-run 'cdkd bootstrap' with kms:CreateKey, kms:PutKeyPolicy, kms:CreateAlias and kms:DescribeKey to create it.`);
|
|
633
|
+
return "failed";
|
|
634
|
+
};
|
|
635
|
+
try {
|
|
636
|
+
const meta = (await kms.send(new DescribeKeyCommand({ KeyId: NOECHO_MAC_KEY_ALIAS }))).KeyMetadata;
|
|
637
|
+
if (meta?.KeySpec === "HMAC_256" && meta.KeyUsage === "GENERATE_VERIFY_MAC" && meta.KeyState === "Enabled") {
|
|
638
|
+
report(`NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} already exists`);
|
|
639
|
+
return "exists";
|
|
640
|
+
}
|
|
641
|
+
warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key (${meta?.KeySpec ?? "unknown spec"}, ${meta?.KeyState ?? "unknown state"}), so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run 'cdkd bootstrap'.`);
|
|
642
|
+
return "failed";
|
|
643
|
+
} catch (error) {
|
|
644
|
+
if (errorName(error) !== "NotFoundException") return failed("kms:DescribeKey", error);
|
|
645
|
+
}
|
|
646
|
+
let keyId;
|
|
647
|
+
try {
|
|
648
|
+
keyId = (await kms.send(new CreateKeyCommand({
|
|
649
|
+
KeySpec: "HMAC_256",
|
|
650
|
+
KeyUsage: "GENERATE_VERIFY_MAC",
|
|
651
|
+
Policy: noEchoMacKeyPolicy(partition, accountId),
|
|
652
|
+
Description: "cdkd: MACs of NoEcho parameter values, so a deploy re-sends a write-only property only when its value changed",
|
|
653
|
+
Tags: [{
|
|
654
|
+
TagKey: "cdkd:purpose",
|
|
655
|
+
TagValue: "noecho-value-mac"
|
|
656
|
+
}]
|
|
657
|
+
}))).KeyMetadata?.KeyId;
|
|
658
|
+
if (keyId === void 0) return failed("kms:CreateKey", /* @__PURE__ */ new Error("no key id"));
|
|
659
|
+
} catch (error) {
|
|
660
|
+
return failed("kms:CreateKey", error);
|
|
661
|
+
}
|
|
662
|
+
try {
|
|
663
|
+
await kms.send(new CreateAliasCommand({
|
|
664
|
+
AliasName: NOECHO_MAC_KEY_ALIAS,
|
|
665
|
+
TargetKeyId: keyId
|
|
666
|
+
}));
|
|
667
|
+
} catch (error) {
|
|
668
|
+
const name = errorName(error);
|
|
669
|
+
await kms.send(new ScheduleKeyDeletionCommand({
|
|
670
|
+
KeyId: keyId,
|
|
671
|
+
PendingWindowInDays: 7
|
|
672
|
+
})).catch((retireError) => warn(`Could not schedule the deletion of the unused KMS key ${keyId} in ${region} (${errorName(retireError)}); schedule it by hand: aws kms schedule-key-deletion --key-id ${keyId} --pending-window-in-days 7 --region ${region}`));
|
|
673
|
+
if (name !== "AlreadyExistsException") return failed("kms:CreateAlias", error);
|
|
674
|
+
try {
|
|
675
|
+
const won = (await kms.send(new DescribeKeyCommand({ KeyId: NOECHO_MAC_KEY_ALIAS }))).KeyMetadata;
|
|
676
|
+
if (won?.KeySpec === "HMAC_256" && won.KeyUsage === "GENERATE_VERIFY_MAC" && won.KeyState === "Enabled") {
|
|
677
|
+
report(`NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS} already exists`);
|
|
678
|
+
return "exists";
|
|
679
|
+
}
|
|
680
|
+
} catch (describeError) {
|
|
681
|
+
return failed("kms:DescribeKey", describeError);
|
|
682
|
+
}
|
|
683
|
+
warn(`${NOECHO_MAC_KEY_ALIAS} in ${region} does not name an enabled HMAC_256 key, so deploys make no NoEcho value MACs. Point the alias at an enabled HMAC_256 key, or delete it and re-run 'cdkd bootstrap'.`);
|
|
684
|
+
return "failed";
|
|
685
|
+
}
|
|
686
|
+
report(`Created the NoEcho value MAC key ${NOECHO_MAC_KEY_ALIAS}`);
|
|
687
|
+
return "created";
|
|
688
|
+
}
|
|
689
|
+
|
|
1220
690
|
// src/cli/commands/bootstrap.ts
|
|
1221
691
|
async function bootstrapCommand(options) {
|
|
1222
692
|
const logger = getLogger();
|
|
@@ -1238,12 +708,17 @@ async function bootstrapCommand(options) {
|
|
|
1238
708
|
let s3Client = awsClients.s3;
|
|
1239
709
|
let bucketName;
|
|
1240
710
|
let accountId;
|
|
711
|
+
let partition;
|
|
1241
712
|
if (options.stateBucket) {
|
|
1242
713
|
bucketName = options.stateBucket;
|
|
1243
|
-
|
|
714
|
+
const identity = await awsClients.sts.send(new GetCallerIdentityCommand({}));
|
|
715
|
+
accountId = identity.Account;
|
|
716
|
+
partition = partitionOfArn$1(identity.Arn);
|
|
1244
717
|
} else {
|
|
1245
718
|
logger.info("No --state-bucket specified, resolving default bucket name...");
|
|
1246
|
-
|
|
719
|
+
const identity = await awsClients.sts.send(new GetCallerIdentityCommand({}));
|
|
720
|
+
accountId = identity.Account;
|
|
721
|
+
partition = partitionOfArn$1(identity.Arn);
|
|
1247
722
|
bucketName = getDefaultStateBucketName(accountId);
|
|
1248
723
|
logger.info(`Using default state bucket: ${bucketName}`);
|
|
1249
724
|
}
|
|
@@ -1284,6 +759,12 @@ async function bootstrapCommand(options) {
|
|
|
1284
759
|
}
|
|
1285
760
|
const rebuiltStateBucketClient = await rebuildClientForBucketRegion(s3Client, bucketName, { ...options.profile && { profile: options.profile } });
|
|
1286
761
|
const stateBucketS3 = rebuiltStateBucketClient ?? s3Client;
|
|
762
|
+
const stateBucketSetup = {
|
|
763
|
+
s3: stateBucketS3,
|
|
764
|
+
bucketName,
|
|
765
|
+
accountId,
|
|
766
|
+
report: (message) => logger.info(message)
|
|
767
|
+
};
|
|
1287
768
|
try {
|
|
1288
769
|
let bucketExists = false;
|
|
1289
770
|
try {
|
|
@@ -1301,6 +782,24 @@ async function bootstrapCommand(options) {
|
|
|
1301
782
|
operation: "HeadBucket"
|
|
1302
783
|
});
|
|
1303
784
|
}
|
|
785
|
+
const kmsClient = new KMSClient({
|
|
786
|
+
...awsClientDefaults({ profile: options.profile }),
|
|
787
|
+
region,
|
|
788
|
+
...options.profile && { profile: options.profile }
|
|
789
|
+
});
|
|
790
|
+
let noEchoMacKey;
|
|
791
|
+
try {
|
|
792
|
+
noEchoMacKey = await ensureNoEchoMacKey({
|
|
793
|
+
kms: kmsClient,
|
|
794
|
+
region,
|
|
795
|
+
accountId,
|
|
796
|
+
partition,
|
|
797
|
+
report: (message) => logger.info(message),
|
|
798
|
+
warn: (message) => logger.warn(message)
|
|
799
|
+
});
|
|
800
|
+
} finally {
|
|
801
|
+
kmsClient.destroy();
|
|
802
|
+
}
|
|
1304
803
|
let skipStateBucketConfig = false;
|
|
1305
804
|
if (bucketExists) {
|
|
1306
805
|
if (!options.force) {
|
|
@@ -1311,45 +810,14 @@ async function bootstrapCommand(options) {
|
|
|
1311
810
|
logger.info(`State bucket ${bucketName} already exists — skipping reconfiguration (use --force to reconfigure)`);
|
|
1312
811
|
skipStateBucketConfig = true;
|
|
1313
812
|
} else logger.info("--force specified, continuing with existing bucket");
|
|
1314
|
-
} else {
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
logger.debug("Enabling bucket versioning...");
|
|
1323
|
-
await stateBucketS3.send(new PutBucketVersioningCommand({
|
|
1324
|
-
Bucket: bucketName,
|
|
1325
|
-
ExpectedBucketOwner: accountId,
|
|
1326
|
-
VersioningConfiguration: { Status: "Enabled" }
|
|
1327
|
-
}));
|
|
1328
|
-
logger.info("✓ Enabled bucket versioning");
|
|
1329
|
-
logger.debug("Enabling bucket encryption...");
|
|
1330
|
-
await stateBucketS3.send(new PutBucketEncryptionCommand({
|
|
1331
|
-
Bucket: bucketName,
|
|
1332
|
-
ExpectedBucketOwner: accountId,
|
|
1333
|
-
ServerSideEncryptionConfiguration: { Rules: [{
|
|
1334
|
-
ApplyServerSideEncryptionByDefault: { SSEAlgorithm: "AES256" },
|
|
1335
|
-
BucketKeyEnabled: true
|
|
1336
|
-
}] }
|
|
1337
|
-
}));
|
|
1338
|
-
logger.info("✓ Enabled bucket encryption (AES-256)");
|
|
1339
|
-
logger.debug("Setting bucket policy...");
|
|
1340
|
-
const bucketPolicy = buildDenyExternalAccessPolicy(bucketName, accountId, await stateBucketS3.config.region());
|
|
1341
|
-
await stateBucketS3.send(new PutBucketPolicyCommand({
|
|
1342
|
-
Bucket: bucketName,
|
|
1343
|
-
ExpectedBucketOwner: accountId,
|
|
1344
|
-
Policy: JSON.stringify(bucketPolicy)
|
|
1345
|
-
}));
|
|
1346
|
-
logger.info("✓ Set bucket policy (deny external access)");
|
|
1347
|
-
logger.debug("Setting custom-resource response lifecycle rule...");
|
|
1348
|
-
const lifecycle = await applyCustomResourceResponseExpiration(stateBucketS3, bucketName, { expectedBucketOwner: accountId });
|
|
1349
|
-
if (lifecycle.status === "failed" || lifecycle.status === "refused") logger.warn(customResourceResponseExpirationWarning(bucketName, lifecycle));
|
|
1350
|
-
else if (lifecycle.status === "added") logger.info(safeMsg`✓ Set lifecycle rule (expire ${CUSTOM_RESOURCE_RESPONSE_PREFIX}/ responses after ${1} day)`);
|
|
1351
|
-
else logger.info(safeMsg`✓ Lifecycle rule ${CUSTOM_RESOURCE_RESPONSE_LIFECYCLE_RULE_ID} already present (left unchanged)`);
|
|
1352
|
-
}
|
|
813
|
+
} else await createStateBucket({
|
|
814
|
+
...stateBucketSetup,
|
|
815
|
+
region
|
|
816
|
+
});
|
|
817
|
+
if (!skipStateBucketConfig) await configureStateBucket({
|
|
818
|
+
...stateBucketSetup,
|
|
819
|
+
region
|
|
820
|
+
});
|
|
1353
821
|
let assetStorage;
|
|
1354
822
|
if (options.assets) {
|
|
1355
823
|
logger.info("\nSetting up cdkd asset storage...");
|
|
@@ -1393,6 +861,7 @@ async function bootstrapCommand(options) {
|
|
|
1393
861
|
logger.info(`Asset bucket: ${assetStorage.assetBucket}`);
|
|
1394
862
|
logger.info(`Container-asset repository: ${assetStorage.containerRepo}`);
|
|
1395
863
|
}
|
|
864
|
+
if (noEchoMacKey === "created" || noEchoMacKey === "exists") logger.info(`NoEcho value MAC key: ${NOECHO_MAC_KEY_ALIAS}`);
|
|
1396
865
|
logger.info(`Region: ${region}`);
|
|
1397
866
|
if (assetStorage) logger.info(`\ncdkd asset storage is now ON for region ${region}: deploys in this region publish assets to the cdkd-owned bucket/repo (out of 'cdk gc' reach) instead of the CDK bootstrap storage. The first deploy of each existing stack with assets will show a one-time UPDATE re-pointing asset references — content is identical, no replacement.`);
|
|
1398
867
|
logger.info("\nYou can now use cdkd deploy with:");
|
|
@@ -1404,7 +873,7 @@ async function bootstrapCommand(options) {
|
|
|
1404
873
|
}
|
|
1405
874
|
}
|
|
1406
875
|
function createBootstrapCommand() {
|
|
1407
|
-
const cmd = new Command("bootstrap").description("Bootstrap cdkd by creating the S3 state bucket plus cdkd-owned asset storage (asset bucket + container-asset ECR repo) for the region. With --destroy, tear down the region's asset storage instead.").option("--state-bucket <bucket>", "Name of S3 bucket to create for state storage (default: cdkd-state-{accountId})").option("--force", "Create: force reconfiguration of an existing bucket. Destroy: delete the asset storage even when deployed stacks still reference it", false).option("--no-assets", "Skip cdkd asset storage (asset bucket / ECR repo / marker) — deploys keep publishing assets to the CDK bootstrap bucket/repo").option("--asset-bucket <name>", "Custom name for the cdkd asset bucket (default: cdkd-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--container-repo <name>", "Custom name for the container-asset ECR repository (default: cdkd-container-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--destroy", "Tear down the region's cdkd asset storage (empty + delete the asset bucket, force-delete the container-asset ECR repo, then delete the bootstrap marker last). The state bucket is kept unless --include-state-bucket is also passed", false).option("--include-state-bucket", "With --destroy: also delete the S3 state bucket. Refused while any stack state exists or any other region is still opted in to asset storage", false).addOption(new Option("--region <region>", "AWS region to bootstrap, or to tear down with --destroy (defaults to AWS_REGION, AWS_DEFAULT_REGION, the profile's region, else us-east-1; an inferred region keeps existing us-east-1 asset storage)")).action(withErrorHandling(async (options) => {
|
|
876
|
+
const cmd = new Command("bootstrap").description("Bootstrap cdkd by creating the S3 state bucket plus cdkd-owned asset storage (asset bucket + container-asset ECR repo) for the region. With --destroy, tear down the region's asset storage instead. Also creates the region's HMAC KMS key that lets deploys tell whether a NoEcho parameter value changed (alias/cdkd-noecho-mac).").option("--state-bucket <bucket>", "Name of S3 bucket to create for state storage (default: cdkd-state-{accountId})").option("--force", "Create: force reconfiguration of an existing bucket. Destroy: delete the asset storage even when deployed stacks still reference it", false).option("--no-assets", "Skip cdkd asset storage (asset bucket / ECR repo / marker) — deploys keep publishing assets to the CDK bootstrap bucket/repo").option("--asset-bucket <name>", "Custom name for the cdkd asset bucket (default: cdkd-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--container-repo <name>", "Custom name for the container-asset ECR repository (default: cdkd-container-assets-{accountId}-{region}). Written into the bootstrap marker; re-bootstrapping a region with a different name is refused").option("--destroy", "Tear down the region's cdkd asset storage (empty + delete the asset bucket, force-delete the container-asset ECR repo, then delete the bootstrap marker last). The state bucket is kept unless --include-state-bucket is also passed", false).option("--include-state-bucket", "With --destroy: also delete the S3 state bucket. Refused while any stack state exists or any other region is still opted in to asset storage", false).addOption(new Option("--region <region>", "AWS region to bootstrap, or to tear down with --destroy (defaults to AWS_REGION, AWS_DEFAULT_REGION, the profile's region, else us-east-1; an inferred region keeps existing us-east-1 asset storage)")).action(withErrorHandling(async (options) => {
|
|
1408
877
|
if (options.destroy) {
|
|
1409
878
|
if (options.assetBucket !== void 0 || options.containerRepo !== void 0) throw new CdkdError("--asset-bucket / --container-repo cannot be combined with --destroy. The teardown reads the region's asset storage names from the bootstrap marker.", "INVALID_OPTIONS");
|
|
1410
879
|
if (!options.assets) throw new CdkdError("--no-assets cannot be combined with --destroy. The teardown scope is the asset storage itself; use --include-state-bucket to also delete the state bucket.", "INVALID_OPTIONS");
|
|
@@ -1430,248 +899,6 @@ function createBootstrapCommand() {
|
|
|
1430
899
|
return cmd;
|
|
1431
900
|
}
|
|
1432
901
|
|
|
1433
|
-
// src/utils/glob-match.ts
|
|
1434
|
-
function globMatches(pattern, subject) {
|
|
1435
|
-
const segments = pattern.split("*");
|
|
1436
|
-
if (segments.length === 1) return pattern === subject;
|
|
1437
|
-
const head = segments[0];
|
|
1438
|
-
const tail = segments[segments.length - 1];
|
|
1439
|
-
if (subject.length < head.length + tail.length) return false;
|
|
1440
|
-
if (!subject.startsWith(head) || !subject.endsWith(tail)) return false;
|
|
1441
|
-
const end = subject.length - tail.length;
|
|
1442
|
-
let cursor = head.length;
|
|
1443
|
-
for (let i = 1; i < segments.length - 1; i++) {
|
|
1444
|
-
const segment = segments[i];
|
|
1445
|
-
if (segment === "") continue;
|
|
1446
|
-
const at = subject.indexOf(segment, cursor);
|
|
1447
|
-
if (at === -1 || at + segment.length > end) return false;
|
|
1448
|
-
cursor = at + segment.length;
|
|
1449
|
-
}
|
|
1450
|
-
return true;
|
|
1451
|
-
}
|
|
1452
|
-
function pathGlobMatches(pattern, subject) {
|
|
1453
|
-
const p = pattern.split("/");
|
|
1454
|
-
const s = subject.split("/");
|
|
1455
|
-
let can = s.map(() => false).concat(true);
|
|
1456
|
-
for (let i = p.length - 1; i >= 0; i--) {
|
|
1457
|
-
const next = new Array(s.length + 1).fill(false);
|
|
1458
|
-
if (p[i] === "**") for (let j = s.length; j >= 0; j--) next[j] = can[j] || j < s.length && next[j + 1];
|
|
1459
|
-
else for (let j = 0; j < s.length; j++) next[j] = can[j + 1] && globMatches(p[i], s[j]);
|
|
1460
|
-
can = next;
|
|
1461
|
-
}
|
|
1462
|
-
return can[0];
|
|
1463
|
-
}
|
|
1464
|
-
|
|
1465
|
-
// src/cli/cdk-path.ts
|
|
1466
|
-
function readCdkPath(resource) {
|
|
1467
|
-
const meta = resource.Metadata;
|
|
1468
|
-
if (!meta) return "";
|
|
1469
|
-
const v = meta["aws:cdk:path"];
|
|
1470
|
-
return typeof v === "string" ? v : "";
|
|
1471
|
-
}
|
|
1472
|
-
function readCdkPathOrUndefined(resource) {
|
|
1473
|
-
const path = readCdkPath(resource);
|
|
1474
|
-
return path === "" ? void 0 : path;
|
|
1475
|
-
}
|
|
1476
|
-
function buildCdkPathIndex(template) {
|
|
1477
|
-
const index = /* @__PURE__ */ new Map();
|
|
1478
|
-
for (const [logicalId, resource] of Object.entries(template.Resources)) {
|
|
1479
|
-
if (resource.Type === "AWS::CDK::Metadata") continue;
|
|
1480
|
-
const path = readCdkPath(resource);
|
|
1481
|
-
if (path) index.set(path, logicalId);
|
|
1482
|
-
}
|
|
1483
|
-
return index;
|
|
1484
|
-
}
|
|
1485
|
-
function resolveCdkPathToLogicalIds(input, index) {
|
|
1486
|
-
const seen = /* @__PURE__ */ new Map();
|
|
1487
|
-
const prefix = `${input}/`;
|
|
1488
|
-
for (const [path, logicalId] of index) if (path === input || path.startsWith(prefix)) {
|
|
1489
|
-
if (!seen.has(logicalId)) seen.set(logicalId, path);
|
|
1490
|
-
}
|
|
1491
|
-
return [...seen.entries()].map(([logicalId, cdkPath]) => ({
|
|
1492
|
-
logicalId,
|
|
1493
|
-
cdkPath
|
|
1494
|
-
}));
|
|
1495
|
-
}
|
|
1496
|
-
function stackForConstructPath(path, stacks) {
|
|
1497
|
-
let best;
|
|
1498
|
-
let bestRank = -1;
|
|
1499
|
-
for (const s of stacks) {
|
|
1500
|
-
const names = [[s.displayName, 1], [s.stackName, 0]];
|
|
1501
|
-
for (const [name, preference] of names) {
|
|
1502
|
-
if (typeof name !== "string" || name.length === 0) continue;
|
|
1503
|
-
if (!path.startsWith(`${name}/`)) continue;
|
|
1504
|
-
const rank = name.length * 2 + preference;
|
|
1505
|
-
if (rank > bestRank) {
|
|
1506
|
-
best = s;
|
|
1507
|
-
bestRank = rank;
|
|
1508
|
-
}
|
|
1509
|
-
}
|
|
1510
|
-
}
|
|
1511
|
-
return best;
|
|
1512
|
-
}
|
|
1513
|
-
function stackForPathFormTarget(parsed, target, stacks) {
|
|
1514
|
-
if (!parsed.isPath || parsed.pathOrId !== target) return void 0;
|
|
1515
|
-
return stackForConstructPath(parsed.pathOrId, stacks);
|
|
1516
|
-
}
|
|
1517
|
-
|
|
1518
|
-
// src/cli/stack-matcher.ts
|
|
1519
|
-
function matchStacks(stacks, patterns, options = {}) {
|
|
1520
|
-
if (patterns.length === 0) return [];
|
|
1521
|
-
const selected = /* @__PURE__ */ new Set();
|
|
1522
|
-
for (const pattern of patterns) for (const stack of stacksForPattern(stacks, pattern)) selected.add(stack);
|
|
1523
|
-
if (options.dedupe === "identity") return stacks.filter((s) => selected.has(s));
|
|
1524
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1525
|
-
return stacks.filter((s) => selected.has(s) && !seen.has(s.stackName) && seen.add(s.stackName));
|
|
1526
|
-
}
|
|
1527
|
-
function stackNameRegionCollisions(stacks, regionOf, selected = new Set(stacks)) {
|
|
1528
|
-
const byNameRegion = /* @__PURE__ */ new Map();
|
|
1529
|
-
for (const stack of stacks) {
|
|
1530
|
-
const key = injectiveKey(stack.stackName, regionOf(stack) ?? "");
|
|
1531
|
-
const group = byNameRegion.get(key);
|
|
1532
|
-
if (group) group.push(stack);
|
|
1533
|
-
else byNameRegion.set(key, [stack]);
|
|
1534
|
-
}
|
|
1535
|
-
const sameAccountPossible = (a, b) => a.account === void 0 || b.account === void 0 || a.account === b.account;
|
|
1536
|
-
const groups = [];
|
|
1537
|
-
for (const group of byNameRegion.values()) {
|
|
1538
|
-
const chosen = group.filter((s) => selected.has(s));
|
|
1539
|
-
if (chosen.length === 0) continue;
|
|
1540
|
-
const colliding = group.filter((s) => selected.has(s) || chosen.some((c) => sameAccountPossible(c, s)));
|
|
1541
|
-
if (colliding.length > 1) groups.push(colliding);
|
|
1542
|
-
}
|
|
1543
|
-
return groups;
|
|
1544
|
-
}
|
|
1545
|
-
function stacksForDependency(depName, dependent, pool) {
|
|
1546
|
-
if (depName === dependent.stackName) return [];
|
|
1547
|
-
const candidates = pool.filter((s) => s.stackName === depName);
|
|
1548
|
-
if (candidates.length <= 1) return candidates;
|
|
1549
|
-
const sameStage = candidates.filter((s) => s.stagePath === dependent.stagePath);
|
|
1550
|
-
const inStage = sameStage.length > 0 ? sameStage : candidates;
|
|
1551
|
-
if (inStage.length === 1) return inStage;
|
|
1552
|
-
const sameRegion = inStage.filter((s) => s.region === dependent.region);
|
|
1553
|
-
return sameRegion.length > 0 ? sameRegion : inStage;
|
|
1554
|
-
}
|
|
1555
|
-
function renderStackNameRegionCollision(groups, regionOf) {
|
|
1556
|
-
const ident = (v) => displayIdent(v, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
|
|
1557
|
-
return `Selected stacks address the same CloudFormation stack: ${groups.map((group) => {
|
|
1558
|
-
const region = regionOf(group[0]);
|
|
1559
|
-
const where = region === void 0 ? "and neither sets env.region, so they deploy to the same region" : `in region ${ident(region)}`;
|
|
1560
|
-
const accounts = [...new Set(group.flatMap((s) => s.account ? [s.account] : []))];
|
|
1561
|
-
const accountNote = accounts.length > 1 ? ` (their accounts ${accounts.map(ident).join(", ")} differ, but one run deploys every selected stack under its own account)` : "";
|
|
1562
|
-
return `${group.map(describeStack).join(", ")} share the physical stack name ${ident(group[0].stackName)} ${where}${accountNote}`;
|
|
1563
|
-
}).join("; ")}. Give each a distinct stackName or env.region, or select only one of them by its CDK path.` + (groups.some((g) => g.some((s) => s.region === void 0 && regionOf(s) !== void 0)) ? " A stack without env.region takes the run's region: pin that Stage's region, or set AWS_REGION to another region for this run." : "");
|
|
1564
|
-
}
|
|
1565
|
-
function refuseStackNameRegionCollisions(stacks, regionOf, selected) {
|
|
1566
|
-
const groups = stackNameRegionCollisions(stacks, regionOf, selected);
|
|
1567
|
-
if (groups.length > 0) throw new CdkdError(renderStackNameRegionCollision(groups, (s) => regionOf(s)), "STACK_NAME_REGION_COLLISION");
|
|
1568
|
-
}
|
|
1569
|
-
function selectTargetStack(parsed, target, stacks) {
|
|
1570
|
-
if (parsed.stackPattern === null) return stacks.length === 1 ? {
|
|
1571
|
-
kind: "found",
|
|
1572
|
-
stack: stacks[0]
|
|
1573
|
-
} : { kind: "no-prefix" };
|
|
1574
|
-
const byPrefix = stackForPathFormTarget(parsed, target, stacks);
|
|
1575
|
-
if (byPrefix) {
|
|
1576
|
-
if (stackForPathFormTarget(parsed, target, [...stacks].reverse()) === byPrefix) return {
|
|
1577
|
-
kind: "found",
|
|
1578
|
-
stack: byPrefix
|
|
1579
|
-
};
|
|
1580
|
-
return {
|
|
1581
|
-
kind: "ambiguous",
|
|
1582
|
-
pattern: byPrefix.stackName,
|
|
1583
|
-
matched: stacks.filter((s) => s.stackName === byPrefix.stackName)
|
|
1584
|
-
};
|
|
1585
|
-
}
|
|
1586
|
-
const matched = matchStacks([...stacks], [parsed.stackPattern], { dedupe: "identity" });
|
|
1587
|
-
if (matched.length === 1) return {
|
|
1588
|
-
kind: "found",
|
|
1589
|
-
stack: matched[0]
|
|
1590
|
-
};
|
|
1591
|
-
if (matched.length === 0) return {
|
|
1592
|
-
kind: "not-found",
|
|
1593
|
-
pattern: parsed.stackPattern
|
|
1594
|
-
};
|
|
1595
|
-
return {
|
|
1596
|
-
kind: "ambiguous",
|
|
1597
|
-
pattern: parsed.stackPattern,
|
|
1598
|
-
matched
|
|
1599
|
-
};
|
|
1600
|
-
}
|
|
1601
|
-
function renderAmbiguousTargetStack(pattern, matched) {
|
|
1602
|
-
const sharedName = matched.length > 1 && matched.every((s) => s.stackName === pattern);
|
|
1603
|
-
const example = matched.find((s) => s.displayName && s.displayName !== s.stackName)?.displayName;
|
|
1604
|
-
const hint = example !== void 0 && displayIdent(example, { maxCodePoints: 1152 }) === example ? ` (e.g. '${example}/<construct path>')` : "";
|
|
1605
|
-
return `Stack pattern ${renderPatternList([pattern])} matched ${matched.length} stacks: ${matched.map(describeStack).join(", ")}` + (sharedName ? ", which share that physical stack name" : "") + (example !== void 0 ? `. Name one stack by its CDK path, shown in parentheses${hint}.` : ". Use a more specific pattern.");
|
|
1606
|
-
}
|
|
1607
|
-
function stacksForPattern(stacks, pattern) {
|
|
1608
|
-
const byId = stacks.filter((s) => pathGlobMatches(pattern, s.displayName ?? s.stackName));
|
|
1609
|
-
return byId.length > 0 ? byId : stacks.filter((s) => s.stackName === pattern);
|
|
1610
|
-
}
|
|
1611
|
-
function describeStack(stack) {
|
|
1612
|
-
const name = displayIdent(stack.stackName, { maxCodePoints: STACK_REF_MAX_CODE_POINTS });
|
|
1613
|
-
if (stack.displayName && stack.displayName !== stack.stackName) return `${name} (${displayIdent(stack.displayName, { maxCodePoints: STACK_REF_MAX_CODE_POINTS })})`;
|
|
1614
|
-
return name;
|
|
1615
|
-
}
|
|
1616
|
-
function renderNoStackMatch(patterns, available) {
|
|
1617
|
-
return patterns.length > 0 ? `No stacks matching ${patterns.join(", ")} found in assembly. ` + (available.length > 0 ? `Available: ${available.map(describeStack).join(", ")}` : "The assembly has no stacks") : "No stacks found in assembly";
|
|
1618
|
-
}
|
|
1619
|
-
function unmatchedPatterns(stacks, patterns, isPresent = () => true) {
|
|
1620
|
-
return [...new Set(patterns)].filter((p) => !stacksForPattern(stacks, p).some(isPresent));
|
|
1621
|
-
}
|
|
1622
|
-
function renderUnmatchedPatternsWarning(unmatched, where) {
|
|
1623
|
-
const verb = unmatched.length === 1 ? "was" : "were";
|
|
1624
|
-
return `${renderPatternList(unmatched)} matched no stack ${where} and ${verb} skipped.`;
|
|
1625
|
-
}
|
|
1626
|
-
function renderNotInAppWarning(names) {
|
|
1627
|
-
const one = names.length === 1;
|
|
1628
|
-
return `${renderPatternList(names)} ${one ? "is" : "are"} in state but ${one ? "is not a stack" : "are not stacks"} of this app and ${one ? "was" : "were"} skipped. A nested stack is destroyed with its parent; another app's stack, with that app or by name through cdkd state destroy.`;
|
|
1629
|
-
}
|
|
1630
|
-
function renderPatternList(patterns) {
|
|
1631
|
-
return patterns.map((p) => displayIdent(p, {
|
|
1632
|
-
maxCodePoints: STACK_REF_MAX_CODE_POINTS,
|
|
1633
|
-
listMember: true
|
|
1634
|
-
})).join(", ");
|
|
1635
|
-
}
|
|
1636
|
-
function stackMatchesPattern(stack, pattern) {
|
|
1637
|
-
return pathGlobMatches(pattern, stack.displayName ?? stack.stackName) || pattern === stack.stackName;
|
|
1638
|
-
}
|
|
1639
|
-
function partitionTopLevel(stacks) {
|
|
1640
|
-
const topLevel = [];
|
|
1641
|
-
const inStages = [];
|
|
1642
|
-
for (const stack of stacks) (stack.stagePath === void 0 ? topLevel : inStages).push(stack);
|
|
1643
|
-
return {
|
|
1644
|
-
topLevel,
|
|
1645
|
-
inStages
|
|
1646
|
-
};
|
|
1647
|
-
}
|
|
1648
|
-
function renderAllLeftOutStageStacks(inStages) {
|
|
1649
|
-
const n = inStages.length;
|
|
1650
|
-
return `--all selects top-level stacks only; ${n} stack${n === 1 ? "" : "s"} inside a CDK Stage ${n === 1 ? "was" : "were"} left out (${inStages.map(describeStack).join(", ")}). ` + renderStagePatternAdvice(inStages);
|
|
1651
|
-
}
|
|
1652
|
-
function renderStagePatternAdvice(inStages) {
|
|
1653
|
-
const stagePatterns = [...new Set(inStages.map((s) => s.stagePath).filter((p) => p !== void 0 && displayIdent(p, { maxCodePoints: 1152 }) === p))].map((p) => `'${p}/*'`);
|
|
1654
|
-
return stagePatterns.length > 0 ? `Name them with ${stagePatterns.join(", ")}, or select every stack with '**'.` : `Select them with '**'.`;
|
|
1655
|
-
}
|
|
1656
|
-
function stacksNoLongerSelected(stacks, patterns, selected) {
|
|
1657
|
-
const oldRule = (p, s) => globMatches(p, p.includes("/") ? s.displayName ?? s.stackName : s.stackName);
|
|
1658
|
-
const dropped = stacks.filter((s) => !selected.has(s.stackName) && patterns.some((p) => oldRule(p, s)));
|
|
1659
|
-
return {
|
|
1660
|
-
stacks: dropped,
|
|
1661
|
-
patterns: [...new Set(patterns)].filter((p) => dropped.some((s) => oldRule(p, s)))
|
|
1662
|
-
};
|
|
1663
|
-
}
|
|
1664
|
-
function renderStacksNoLongerSelected(patterns, dropped) {
|
|
1665
|
-
const n = dropped.length;
|
|
1666
|
-
const one = patterns.length === 1;
|
|
1667
|
-
const inStages = dropped.filter((s) => s.stagePath !== void 0);
|
|
1668
|
-
const direct = (s) => s.stagePath !== void 0 && (s.displayName ?? s.stackName).split("/").length === s.stagePath.split("/").length + 1;
|
|
1669
|
-
return `${renderPatternList(patterns)} now ${one ? "matches" : "match"} the CDK path, with * inside one segment, and no longer ${one ? "selects" : "select"} ${n} stack${n === 1 ? "" : "s"} ${one ? "it" : "they"} used to (${dropped.map(describeStack).join(", ")}). ` + (inStages.length === dropped.length && inStages.every(direct) ? renderStagePatternAdvice(inStages) : inStages.length > 0 ? "Name each by the CDK path shown in parentheses, or select every stack with '**'." : "Name each by the CDK path shown in parentheses.");
|
|
1670
|
-
}
|
|
1671
|
-
function renderAllNoTopLevelStacks(inStages) {
|
|
1672
|
-
return `--all selects top-level stacks only, and this app has none: every stack is inside a CDK Stage (${inStages.map(describeStack).join(", ")}). ` + renderStagePatternAdvice(inStages);
|
|
1673
|
-
}
|
|
1674
|
-
|
|
1675
902
|
// src/utils/yaml.ts
|
|
1676
903
|
const EMIT_OPTIONS = {
|
|
1677
904
|
schema: "core",
|
|
@@ -2209,7 +1436,7 @@ function collectCrossStackRefs(node, onRef, unconditional) {
|
|
|
2209
1436
|
// src/provisioning/register-providers.ts
|
|
2210
1437
|
let providerClasses;
|
|
2211
1438
|
function loadProviderClasses() {
|
|
2212
|
-
providerClasses ??= import("./provider-classes-
|
|
1439
|
+
providerClasses ??= import("./provider-classes-CRCHL04N.js");
|
|
2213
1440
|
return providerClasses;
|
|
2214
1441
|
}
|
|
2215
1442
|
function registerAllProviders(registry, classes) {
|
|
@@ -2986,16 +2213,58 @@ var ExportIndexStore = class {
|
|
|
2986
2213
|
}
|
|
2987
2214
|
};
|
|
2988
2215
|
|
|
2989
|
-
// src/cli/commands/
|
|
2990
|
-
async function
|
|
2991
|
-
|
|
2992
|
-
const
|
|
2993
|
-
const
|
|
2994
|
-
const
|
|
2995
|
-
|
|
2996
|
-
|
|
2997
|
-
|
|
2998
|
-
|
|
2216
|
+
// src/cli/commands/emulator-auto-bootstrap.ts
|
|
2217
|
+
async function ensureAwsEmulatorStateBucket(args) {
|
|
2218
|
+
if (!awsEndpointOverrideActive()) return void 0;
|
|
2219
|
+
const logger = getLogger();
|
|
2220
|
+
const accountId = (await args.sts.send(new GetCallerIdentityCommand({}))).Account;
|
|
2221
|
+
const bucketName = resolveStateBucketWithSource(args.cliBucket)?.bucket ?? getDefaultStateBucketName(accountId);
|
|
2222
|
+
try {
|
|
2223
|
+
await args.s3.send(new HeadBucketCommand({ Bucket: bucketName }));
|
|
2224
|
+
return;
|
|
2225
|
+
} catch (error) {
|
|
2226
|
+
const name = error.name;
|
|
2227
|
+
if (name !== "NotFound" && name !== "NoSuchBucket") return void 0;
|
|
2228
|
+
}
|
|
2229
|
+
const setup = {
|
|
2230
|
+
s3: args.s3,
|
|
2231
|
+
bucketName,
|
|
2232
|
+
accountId,
|
|
2233
|
+
region: args.region,
|
|
2234
|
+
report: (message) => logger.debug(message)
|
|
2235
|
+
};
|
|
2236
|
+
try {
|
|
2237
|
+
try {
|
|
2238
|
+
await createStateBucket(setup);
|
|
2239
|
+
} catch (error) {
|
|
2240
|
+
const code = error.name;
|
|
2241
|
+
if (code !== "BucketAlreadyOwnedByYou" && code !== "BucketAlreadyExists") throw error;
|
|
2242
|
+
}
|
|
2243
|
+
await configureStateBucket(setup);
|
|
2244
|
+
} catch (error) {
|
|
2245
|
+
const msg = error instanceof Error ? error.message : String(error);
|
|
2246
|
+
throw new CdkdError(safeMsg`AWS Emulator auto-bootstrap of state bucket ${bucketName} failed: ${msg}. ` + "Run `cdkd bootstrap --aws-emulator --force` to retry.", "AWS_EMULATOR_BOOTSTRAP_FAILED", error instanceof Error ? error : void 0);
|
|
2247
|
+
}
|
|
2248
|
+
logger.info(safeMsg`AWS Emulator had no cdkd bootstrap; bootstrapped it (state bucket ${bucketName}).`);
|
|
2249
|
+
return bucketName;
|
|
2250
|
+
}
|
|
2251
|
+
|
|
2252
|
+
// src/cli/commands/deploy/prep.ts
|
|
2253
|
+
async function prepareStateInfra(args) {
|
|
2254
|
+
const { options, region, effectiveRegion, awsClients, logger } = args;
|
|
2255
|
+
if (!options.dryRun) await ensureAwsEmulatorStateBucket({
|
|
2256
|
+
cliBucket: options.stateBucket,
|
|
2257
|
+
region,
|
|
2258
|
+
s3: awsClients.s3,
|
|
2259
|
+
sts: awsClients.sts
|
|
2260
|
+
});
|
|
2261
|
+
const resolvedStateBucket = await resolveStateBucketWithDefaultAndSource(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
|
|
2262
|
+
const stateBucket = resolvedStateBucket.bucket;
|
|
2263
|
+
const preflightStateBackend = new S3StateBackend(awsClients.s3, {
|
|
2264
|
+
bucket: stateBucket,
|
|
2265
|
+
prefix: options.statePrefix
|
|
2266
|
+
}, {
|
|
2267
|
+
region,
|
|
2999
2268
|
...options.profile && { profile: options.profile }
|
|
3000
2269
|
});
|
|
3001
2270
|
await preflightStateBackend.verifyBucketExists({ existenceAlreadyProbed: stateBucketExistenceConfirmed(resolvedStateBucket) });
|
|
@@ -3663,6 +2932,67 @@ function splitUpdatePartial(result) {
|
|
|
3663
2932
|
nestedUpdatePartial
|
|
3664
2933
|
};
|
|
3665
2934
|
}
|
|
2935
|
+
async function confirmAutoAssetStorageCreate(args) {
|
|
2936
|
+
const { assetRegion, accountId } = args;
|
|
2937
|
+
const logger = getLogger();
|
|
2938
|
+
if (awsEndpointOverrideActive()) {
|
|
2939
|
+
logger.info(safeMsg`Creating cdkd asset storage for region '${assetRegion}' in AWS Emulator ` + `(no prompt under --aws-emulator; opt out with --no-auto-asset-storage).`);
|
|
2940
|
+
return true;
|
|
2941
|
+
}
|
|
2942
|
+
if (args.yes || !process.stdin.isTTY) {
|
|
2943
|
+
logger.info(safeMsg`Creating cdkd asset storage for region '${assetRegion}' (first deploy into this ` + `region; opt out with --no-auto-asset-storage).`);
|
|
2944
|
+
return true;
|
|
2945
|
+
}
|
|
2946
|
+
return promptYesNo(`Region '${assetRegion}' has no cdkd asset storage yet. Create it now (S3 bucket cdkd-assets-${accountId}-${assetRegion} + container-asset ECR repo, out of 'cdk gc' reach)?`);
|
|
2947
|
+
}
|
|
2948
|
+
const FORCE_QUIT_ABORT_BUDGET_MS = 5e3;
|
|
2949
|
+
function exitAfterAbortingUploads(exit, write, abort = abortInFlightMultipartUploads, budgetMs = FORCE_QUIT_ABORT_BUDGET_MS) {
|
|
2950
|
+
let started;
|
|
2951
|
+
try {
|
|
2952
|
+
started = abort();
|
|
2953
|
+
} catch {
|
|
2954
|
+
started = {
|
|
2955
|
+
destinations: [],
|
|
2956
|
+
done: Promise.resolve()
|
|
2957
|
+
};
|
|
2958
|
+
}
|
|
2959
|
+
const { destinations } = started;
|
|
2960
|
+
let exited = false;
|
|
2961
|
+
const finish = (confirmed) => {
|
|
2962
|
+
if (exited) return;
|
|
2963
|
+
exited = true;
|
|
2964
|
+
if (destinations.length > 0) {
|
|
2965
|
+
const list = destinations.map((d) => displaySafe(d)).join(", ");
|
|
2966
|
+
write(confirmed ? `Interrupted: aborted the in-flight asset upload(s) ${list}.\n` : `Interrupted: exiting before the abort of the in-flight asset upload(s) ${list} was confirmed; the asset bucket's lifecycle rule removes what is left.\n`);
|
|
2967
|
+
}
|
|
2968
|
+
exit(130);
|
|
2969
|
+
};
|
|
2970
|
+
const timer = setTimeout(() => finish(false), budgetMs);
|
|
2971
|
+
return started.done.catch(() => void 0).then(() => {
|
|
2972
|
+
clearTimeout(timer);
|
|
2973
|
+
finish(true);
|
|
2974
|
+
});
|
|
2975
|
+
}
|
|
2976
|
+
function createDeploySigintHandler(options) {
|
|
2977
|
+
const write = options.write ?? ((text) => void process.stderr.write(text));
|
|
2978
|
+
const exit = options.exit ?? ((code) => process.exit(code));
|
|
2979
|
+
let signals = 0;
|
|
2980
|
+
return () => {
|
|
2981
|
+
signals++;
|
|
2982
|
+
if (signals === 1) {
|
|
2983
|
+
write("\nInterrupted — waiting for in-progress operations to complete...\n");
|
|
2984
|
+
options.onFirst();
|
|
2985
|
+
return;
|
|
2986
|
+
}
|
|
2987
|
+
if (signals > 2) {
|
|
2988
|
+
exit(130);
|
|
2989
|
+
return;
|
|
2990
|
+
}
|
|
2991
|
+
write(`
|
|
2992
|
+
Force-quit: stack locks may not be released. If the next run reports a lock, run this for EACH stack it names, in the region-qualified form — see the message that run prints.\nRelease with: ${forceQuitReleaseCommand()}\n`);
|
|
2993
|
+
exitAfterAbortingUploads(exit, write, options.abort, options.budgetMs);
|
|
2994
|
+
};
|
|
2995
|
+
}
|
|
3666
2996
|
|
|
3667
2997
|
// src/cli/commands/deploy/stack-deploy.ts
|
|
3668
2998
|
async function deployStackInScope(ctx, stackInfo, stackRegion, stackAwsClients) {
|
|
@@ -3714,7 +3044,7 @@ async function deployStackInScope(ctx, stackInfo, stackRegion, stackAwsClients)
|
|
|
3714
3044
|
const syncValidation = validateRecreateTargets({
|
|
3715
3045
|
template: stackInfo.template,
|
|
3716
3046
|
state: stateForRecreateCheck?.state ?? {
|
|
3717
|
-
version:
|
|
3047
|
+
version: 17,
|
|
3718
3048
|
stackName: stackInfo.stackName,
|
|
3719
3049
|
region: stackRegion,
|
|
3720
3050
|
resources: {},
|
|
@@ -3749,7 +3079,7 @@ async function deployStackInScope(ctx, stackInfo, stackRegion, stackAwsClients)
|
|
|
3749
3079
|
const replacedReaders = await findReplacedReadersOfRecreateTargets({
|
|
3750
3080
|
template: stackInfo.template,
|
|
3751
3081
|
state: stateForRecreateCheck?.state ?? {
|
|
3752
|
-
version:
|
|
3082
|
+
version: 17,
|
|
3753
3083
|
stackName: stackInfo.stackName,
|
|
3754
3084
|
region: stackRegion,
|
|
3755
3085
|
resources: {},
|
|
@@ -3977,15 +3307,9 @@ async function deployCommand(stacks, options) {
|
|
|
3977
3307
|
const callerIdentityPromise = fetchCallerIdentity(region);
|
|
3978
3308
|
callerIdentityPromise.catch(() => void 0);
|
|
3979
3309
|
let deployInterrupted = false;
|
|
3980
|
-
const topLevelSigintHandler = () => {
|
|
3981
|
-
if (deployInterrupted) {
|
|
3982
|
-
process.stderr.write(`
|
|
3983
|
-
Force-quit: stack locks may not be released. If the next run reports a lock, run this for EACH stack it names, in the region-qualified form — see the message that run prints.\nRelease with: ${forceQuitReleaseCommand()}\n`);
|
|
3984
|
-
process.exit(130);
|
|
3985
|
-
}
|
|
3986
|
-
process.stderr.write("\nInterrupted — waiting for in-progress operations to complete...\n");
|
|
3310
|
+
const topLevelSigintHandler = createDeploySigintHandler({ onFirst: () => {
|
|
3987
3311
|
deployInterrupted = true;
|
|
3988
|
-
};
|
|
3312
|
+
} });
|
|
3989
3313
|
process.on("SIGINT", topLevelSigintHandler);
|
|
3990
3314
|
const unforwardSigterm = forwardSigtermToSigint();
|
|
3991
3315
|
let preflightBackendForCleanup;
|
|
@@ -4102,13 +3426,11 @@ Force-quit: stack locks may not be released. If the next run reports a lock, run
|
|
|
4102
3426
|
const assetPublisher = new AssetPublisher();
|
|
4103
3427
|
const useCdkBootstrapAssets = resolveUseCdkBootstrapAssets(options.useCdkBootstrapAssets);
|
|
4104
3428
|
const autoAssetStorage = resolveAutoAssetStorage(options.autoAssetStorage);
|
|
4105
|
-
const confirmAutoAssetStorage =
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
return promptYesNo(`Region '${assetRegion}' has no cdkd asset storage yet. Create it now (S3 bucket cdkd-assets-${accountId}-${assetRegion} + container-asset ECR repo, out of 'cdk gc' reach)?`);
|
|
4111
|
-
};
|
|
3429
|
+
const confirmAutoAssetStorage = (assetRegion) => confirmAutoAssetStorageCreate({
|
|
3430
|
+
assetRegion,
|
|
3431
|
+
accountId,
|
|
3432
|
+
yes: options.yes === true
|
|
3433
|
+
});
|
|
4112
3434
|
const assetModeResolver = new AssetModeResolver(preflightStateBackend, accountId, {
|
|
4113
3435
|
...options.profile && { profile: options.profile },
|
|
4114
3436
|
...useCdkBootstrapAssets && { useCdkBootstrapAssets: true },
|
|
@@ -4236,6 +3558,7 @@ function createDeployCommand() {
|
|
|
4236
3558
|
...stackOptions,
|
|
4237
3559
|
...deployOptions,
|
|
4238
3560
|
skipFinalSnapshotOption,
|
|
3561
|
+
noLocalCustomResourcesOption,
|
|
4239
3562
|
requireApprovalOption,
|
|
4240
3563
|
outputsFileOption,
|
|
4241
3564
|
...contextOptions,
|
|
@@ -6029,9 +5352,77 @@ function healerUnderRecordPrintingBag(healer, resources, namingSecrets) {
|
|
|
6029
5352
|
return Object.assign((logicalId, resource) => withPrintingSecrets(bagFor(logicalId, resource), () => healer(logicalId, resource)), healer);
|
|
6030
5353
|
}
|
|
6031
5354
|
|
|
5355
|
+
// src/cli/commands/diff-recursive/noecho-macs.ts
|
|
5356
|
+
function macsFor(args) {
|
|
5357
|
+
return createNoEchoValueMacs({
|
|
5358
|
+
template: args.template,
|
|
5359
|
+
parameterValues: args.parameterValues,
|
|
5360
|
+
stackName: args.stackName,
|
|
5361
|
+
region: args.region,
|
|
5362
|
+
stackInstanceId: () => args.stackInstanceId,
|
|
5363
|
+
logger: args.logger,
|
|
5364
|
+
purpose: "diff",
|
|
5365
|
+
...args.client !== void 0 && { client: args.client }
|
|
5366
|
+
})?.macs() ?? Promise.resolve(void 0);
|
|
5367
|
+
}
|
|
5368
|
+
async function previewNoEchoMacChanges(args) {
|
|
5369
|
+
if (args.nestedChild || args.parameterValues === void 0) return [];
|
|
5370
|
+
if (args.sources.parameters.size === 0) return [];
|
|
5371
|
+
const candidates = [];
|
|
5372
|
+
for (const [logicalId, change] of args.changes) {
|
|
5373
|
+
if (change.changeType !== "NO_CHANGE" && change.changeType !== "UPDATE") continue;
|
|
5374
|
+
const record = Object.hasOwn(args.resources, logicalId) ? args.resources[logicalId] : void 0;
|
|
5375
|
+
if (record === void 0 || noEchoValueMacsOf(record).size === 0) continue;
|
|
5376
|
+
candidates.push([
|
|
5377
|
+
logicalId,
|
|
5378
|
+
change,
|
|
5379
|
+
record
|
|
5380
|
+
]);
|
|
5381
|
+
}
|
|
5382
|
+
if (candidates.length === 0) return [];
|
|
5383
|
+
const cacheKey = noEchoMacBinding(args.stackInstanceId, args.stackName, args.region);
|
|
5384
|
+
const cached = args.cache?.get(cacheKey);
|
|
5385
|
+
const current = await (cached ?? macsFor(args));
|
|
5386
|
+
if (cached === void 0) args.cache?.set(cacheKey, Promise.resolve(current));
|
|
5387
|
+
if (current === void 0) return [];
|
|
5388
|
+
const moved = [];
|
|
5389
|
+
const writeOnlyLookups = args.writeOnlyLookups ?? /* @__PURE__ */ new Map();
|
|
5390
|
+
for (const [logicalId, change, record] of candidates) {
|
|
5391
|
+
const templateProps = (args.template.Resources?.[logicalId])?.Properties ?? {};
|
|
5392
|
+
const recorded = noEchoValueMacsOf(record);
|
|
5393
|
+
const fingerprints = maskedPropertyFingerprintsOf(record);
|
|
5394
|
+
const unsettled = new Set(record.unsettledProperties ?? []);
|
|
5395
|
+
const writeOnly = await macWriteOnlyKeys(change.resourceType, writeOnlyLookups);
|
|
5396
|
+
const keys = [];
|
|
5397
|
+
for (const [key, entry] of recorded) {
|
|
5398
|
+
if (!Object.hasOwn(templateProps, key)) continue;
|
|
5399
|
+
if (writeOnly?.has(key) !== true || unsettled.has(key)) continue;
|
|
5400
|
+
if (fingerprints.get(key) !== maskedPropertyFingerprint(templateProps[key])) continue;
|
|
5401
|
+
if ((change.propertyChanges ?? []).some((pc) => pc.path === key)) continue;
|
|
5402
|
+
if (!readsOnlyNoEchoParameters(templateProps[key], args.sources.parameters)) continue;
|
|
5403
|
+
const parameters = noEchoMacParametersOf(templateProps[key], args.sources);
|
|
5404
|
+
if (noEchoMacVerdict(entry, parameters, current) === "changed") keys.push(key);
|
|
5405
|
+
}
|
|
5406
|
+
if (keys.length === 0) continue;
|
|
5407
|
+
const createOnly = await getCreateOnlyPropertyPaths(change.resourceType).catch(() => []);
|
|
5408
|
+
for (const key of keys) {
|
|
5409
|
+
if (createOnly.some((path) => path[0] === key)) continue;
|
|
5410
|
+
change.propertyChanges = [...change.propertyChanges ?? [], {
|
|
5411
|
+
path: key,
|
|
5412
|
+
oldValue: change.currentProperties?.[key],
|
|
5413
|
+
newValue: change.desiredProperties?.[key],
|
|
5414
|
+
requiresReplacement: false
|
|
5415
|
+
}];
|
|
5416
|
+
if (change.changeType === "NO_CHANGE") change.changeType = "UPDATE";
|
|
5417
|
+
moved.push(`${logicalId}.${key}`);
|
|
5418
|
+
}
|
|
5419
|
+
}
|
|
5420
|
+
return moved;
|
|
5421
|
+
}
|
|
5422
|
+
|
|
6032
5423
|
// src/cli/commands/diff-recursive/compute-stack-diff.ts
|
|
6033
5424
|
async function computeStackDiff(currentState, template, region, stackName, stateBackend, diffCalculator, options = {}) {
|
|
6034
|
-
const { parameters, canonicalizeProperties, ccRouteUnavailableReason, cfnFallback, producerLookup, consumerAccount, inheritSecretBearingTemplate, inheritedSecrets, inheritedSecretTokens, inheritedDerivedNames, attributeHealer: unboundAttributeHealer, parentUnresolvedParameters, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict } = options;
|
|
5425
|
+
const { parameters, canonicalizeProperties, ccRouteUnavailableReason, cfnFallback, producerLookup, consumerAccount, noEchoMacCache, macWriteOnlyLookups, inheritSecretBearingTemplate, inheritedSecrets, inheritedSecretTokens, inheritedDerivedNames, attributeHealer: unboundAttributeHealer, parentUnresolvedParameters, inheritedNoEchoParameters, inheritedNoEchoParametersAnyVerdict } = options;
|
|
6035
5426
|
let healResources = currentState.resources ?? {};
|
|
6036
5427
|
let healNamingSecrets;
|
|
6037
5428
|
const attributeHealer = unboundAttributeHealer && healerUnderRecordPrintingBag(unboundAttributeHealer, () => healResources, (map) => healNamingSecrets?.(map));
|
|
@@ -6184,6 +5575,25 @@ async function computeStackDiff(currentState, template, region, stackName, state
|
|
|
6184
5575
|
...options.inheritedReferenceProvenance && { inherited: options.inheritedReferenceProvenance },
|
|
6185
5576
|
crossStackOutputs: crossStackOutputProvenanceSource(crossStackReads, crossStackReads, stateBackend)
|
|
6186
5577
|
});
|
|
5578
|
+
const macConditions = conditions === void 0 ? void 0 : Object.fromEntries(Object.entries(conditions).filter(([name]) => !stillUnknown.includes(name)));
|
|
5579
|
+
const macMoved = await previewNoEchoMacChanges({
|
|
5580
|
+
changes,
|
|
5581
|
+
template: effectiveTemplate,
|
|
5582
|
+
resources: stateForDiff.resources,
|
|
5583
|
+
parameterValues: mergedParameters,
|
|
5584
|
+
sources: {
|
|
5585
|
+
parameters: noEchoParametersOf(effectiveTemplate),
|
|
5586
|
+
...macConditions !== void 0 && { conditions: macConditions }
|
|
5587
|
+
},
|
|
5588
|
+
nestedChild: inheritedSecrets !== void 0 || inheritedNoEchoParameters !== void 0,
|
|
5589
|
+
stackName,
|
|
5590
|
+
region,
|
|
5591
|
+
stackInstanceId: stateForDiff.stackInstanceId,
|
|
5592
|
+
logger,
|
|
5593
|
+
...noEchoMacCache !== void 0 && { cache: noEchoMacCache },
|
|
5594
|
+
...macWriteOnlyLookups !== void 0 && { writeOnlyLookups: macWriteOnlyLookups }
|
|
5595
|
+
});
|
|
5596
|
+
if (macMoved.length > 0) logger.info(safeMsg`Stack ${displayStackName(stackName)}: ${macMoved.sort().join(", ")} read a NoEcho parameter whose value changed since the last deploy (its recorded MAC differs): the deploy sends it.`);
|
|
6187
5597
|
const noEchoReaders = Object.keys(effectiveTemplate.Resources ?? {}).filter((logicalId) => changes.get(logicalId)?.changeType === "NO_CHANGE" && readsNoEchoSource(effectiveTemplate.Resources?.[logicalId]?.Properties, {
|
|
6188
5598
|
parameters: noEchoParametersOf(effectiveTemplate),
|
|
6189
5599
|
...conditions !== void 0 && { conditions: Object.fromEntries(Object.entries(conditions).filter(([name]) => !stillUnknown.includes(name))) }
|
|
@@ -6356,7 +5766,7 @@ async function loadStateOrEmpty(stackName, region, stateBackend, refusalRecovery
|
|
|
6356
5766
|
region,
|
|
6357
5767
|
resources: {},
|
|
6358
5768
|
outputs: {},
|
|
6359
|
-
version:
|
|
5769
|
+
version: 17,
|
|
6360
5770
|
lastModified: Date.now()
|
|
6361
5771
|
},
|
|
6362
5772
|
unreadable: [],
|
|
@@ -7768,7 +7178,7 @@ function abandonedScanWarning(subject, verdict) {
|
|
|
7768
7178
|
}
|
|
7769
7179
|
function abandonedScanStackNote(verdict, scans) {
|
|
7770
7180
|
const subject = `${scans} abandoned scan(s) above`;
|
|
7771
|
-
return verdict === "count" ? `${subject}: the resolver stops at the first {{resolve:...}} token it cannot fetch, so any secret after it in the same value recorded no needle and could not be rewritten. Re-run with --verbose for the cause of each
|
|
7181
|
+
return verdict === "count" ? `${subject}: the resolver stops at the first {{resolve:...}} token it cannot fetch, so any secret after it in the same value recorded no needle and could not be rewritten. ` + verboseAwareText("Re-run with --verbose for the cause of each.", "The cause of each is in the debug output above.") : `${subject}: the scan stopped on something cdkd scrub cannot resolve with template defaults alone — an unresolvable Ref or Fn::GetAtt, a parameter with no Default, or a reference whose own argument still holds an unsubstituted \${...}. These do NOT fail --fail, because scrub takes no --parameters and a gate failure here could not be cleared. Give the parameter a Default, or resolve the reference, to let scrub certify these records; otherwise accept that it cannot.`;
|
|
7772
7182
|
}
|
|
7773
7183
|
function abandonedScanVerdict(source, err) {
|
|
7774
7184
|
if (!carriesDynamicReference(source)) return "silent";
|
|
@@ -8940,7 +8350,7 @@ async function scrubStackRewritePass({ stack, region, stateBackend, opts, logger
|
|
|
8940
8350
|
const resolved = nestedRowParameters.get(logicalId);
|
|
8941
8351
|
const parameters = resolved?.complete === true ? nestedChildParameters(resolved.value) : void 0;
|
|
8942
8352
|
if (parameters === void 0) {
|
|
8943
|
-
refuse(`the Parameters ${shownStack} passes it could not be resolved to the values a deploy would hand it, so what it inherited is unknown`,
|
|
8353
|
+
refuse(`the Parameters ${shownStack} passes it could not be resolved to the values a deploy would hand it, so what it inherited is unknown`, verboseAwareText("Re-run cdkd scrub with --verbose to see which value failed to resolve, and fix that.", "The debug output above shows which value failed to resolve; fix that."));
|
|
8944
8354
|
continue;
|
|
8945
8355
|
}
|
|
8946
8356
|
nestedChildren.push({
|
|
@@ -12590,7 +12000,7 @@ function createIamPrincipalUniqueIdResolver(awsClients) {
|
|
|
12590
12000
|
const denied = /^AccessDenied|^NotAuthorized/i.test(name) || status === 403;
|
|
12591
12001
|
if (!warnedOnDenied && denied) {
|
|
12592
12002
|
warnedOnDenied = true;
|
|
12593
|
-
getLogger().warn(`Cannot read IAM principals (${name || "access denied"}). A resource policy whose principal AWS rendered as a unique id (AROA…/AIDA…) may therefore report drift that is only a spelling difference; grant iam:GetRole / iam:GetUser to resolve it, or re-run with --verbose for the full error.`);
|
|
12003
|
+
getLogger().warn(`Cannot read IAM principals (${name || "access denied"}). A resource policy whose principal AWS rendered as a unique id (AROA…/AIDA…) may therefore report drift that is only a spelling difference; grant iam:GetRole / iam:GetUser to resolve ` + safeMsg`it${verboseAwareText(", or re-run with --verbose for the full error", " (the full error is in the debug output)")}.`);
|
|
12594
12004
|
}
|
|
12595
12005
|
getLogger().debug(`Could not resolve the unique id of principal ${displayIdent(arn, { maxCodePoints: 613 })} (${displayAwsMessage(message)}); leaving the policy principal comparison untouched.`);
|
|
12596
12006
|
if (isThrottlingError(error)) return void 0;
|
|
@@ -13924,7 +13334,7 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
|
|
|
13924
13334
|
throw setupError;
|
|
13925
13335
|
}
|
|
13926
13336
|
}
|
|
13927
|
-
return destroyStackUnderLock({
|
|
13337
|
+
return withCustomResourceStack(stackName, () => destroyStackUnderLock({
|
|
13928
13338
|
stackName,
|
|
13929
13339
|
state,
|
|
13930
13340
|
ctx,
|
|
@@ -13939,7 +13349,7 @@ async function destroyStackInRegion(stackName, state, ctx, stackScope) {
|
|
|
13939
13349
|
destroyProviderRegistry,
|
|
13940
13350
|
destroyAwsClients,
|
|
13941
13351
|
restoreBaseRegionAndClients
|
|
13942
|
-
});
|
|
13352
|
+
}));
|
|
13943
13353
|
}
|
|
13944
13354
|
|
|
13945
13355
|
// src/cli/commands/destroy-skip-message.ts
|
|
@@ -14590,6 +14000,7 @@ function createDestroyCommand() {
|
|
|
14590
14000
|
exclusivelyOption("destroy"),
|
|
14591
14001
|
...resourceTimeoutOptions,
|
|
14592
14002
|
skipFinalSnapshotOption,
|
|
14003
|
+
noLocalCustomResourcesOption,
|
|
14593
14004
|
...contextOptions
|
|
14594
14005
|
].forEach((opt) => cmd.addOption(opt));
|
|
14595
14006
|
cmd.addOption(deprecatedRegionOption);
|
|
@@ -19800,7 +19211,8 @@ function createStateDestroyCommand() {
|
|
|
19800
19211
|
...stateOptions,
|
|
19801
19212
|
...resourceTimeoutOptions,
|
|
19802
19213
|
allowUnsupportedTypesOption,
|
|
19803
|
-
skipFinalSnapshotOption
|
|
19214
|
+
skipFinalSnapshotOption,
|
|
19215
|
+
noLocalCustomResourcesOption
|
|
19804
19216
|
].forEach((opt) => cmd.addOption(opt));
|
|
19805
19217
|
cmd.addOption(deprecatedRegionOption);
|
|
19806
19218
|
return cmd;
|
|
@@ -21091,7 +20503,7 @@ function refuseDivergentRecordRegionForRollback(state, stackName, keyRegion, div
|
|
|
21091
20503
|
const resourceCount = isReadableBag(state.resources) ? Object.keys(state.resources).length : void 0;
|
|
21092
20504
|
if (resourceCount === 0 && provenOrphans === 0) return;
|
|
21093
20505
|
const lists = resourceCount === void 0 ? "its resources map cannot be read" : resourceCount > 0 ? `it still lists ${resourceCount} resource${resourceCount === 1 ? "" : "s"}` : `its journal holds ${provenOrphans} failed create${provenOrphans === 1 ? "" : "s"} whose resource the rollback would delete`;
|
|
21094
|
-
throw markNonRetryable(new CdkdError(`cdkd will not roll back ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(keyRegion, "region")}): the state record read from that region's key carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the key's, and ${lists} — so cdkd cannot tell which region they are in. cdkd stamps the key's region into every record it writes, so this record was not written by cdkd. The replay would issue every delete and revert against the key's region; if the record's own region is the honest half, each delete comes back not-found, which the replay reads as ALREADY DELETED — it would report the resource rolled back, drop it from the record, and leave it standing in the other region. Nothing was changed. Re-run with --verbose to see what the record's region field holds, repair that field to match the key it is stored under, and run the rollback again
|
|
20506
|
+
throw markNonRetryable(new CdkdError(`cdkd will not roll back ${plainOrDescribed(stackName, "stack name")} (${plainOrDescribed(keyRegion, "region")}): the state record read from that region's key carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the key's, and ${lists} — so cdkd cannot tell which region they are in. cdkd stamps the key's region into every record it writes, so this record was not written by cdkd. The replay would issue every delete and revert against the key's region; if the record's own region is the honest half, each delete comes back not-found, which the replay reads as ALREADY DELETED — it would report the resource rolled back, drop it from the record, and leave it standing in the other region. Nothing was changed. ` + verboseAwareText("Re-run with --verbose to see what the record's region field holds, ", "The debug output shows what the record's region field holds; ") + "repair that field to match the key it is stored under, and run the rollback again.", STATE_REGION_DIVERGED));
|
|
21095
20507
|
}
|
|
21096
20508
|
function divergedDuringRollbackMessage(divergentBodyRegion) {
|
|
21097
20509
|
return `the state record was rewritten during this rollback, and the rewrite carries a 'region' of its own (${describeRegionValueKind(divergentBodyRegion)}) that is not the region of its key, so cdkd did not write over it`;
|
|
@@ -21373,7 +20785,7 @@ async function runRollbackReplay(ctx) {
|
|
|
21373
20785
|
...carriedState,
|
|
21374
20786
|
...stackInstanceIdCarriedFrom(baseState),
|
|
21375
20787
|
...supersededAfterRollback(baseState, supersededHost),
|
|
21376
|
-
version:
|
|
20788
|
+
version: 17,
|
|
21377
20789
|
region,
|
|
21378
20790
|
resources: { ...stateResources },
|
|
21379
20791
|
...orphansAfterRollback(baseState, mintedOrphans),
|
|
@@ -21619,7 +21031,7 @@ async function rollbackCommand(stackArg, options) {
|
|
|
21619
21031
|
|
|
21620
21032
|
// src/cli/commands/rollback.ts
|
|
21621
21033
|
function createRollbackCommand() {
|
|
21622
|
-
const cmd = new Command("rollback").description("Revert a stack to its pre-deploy state after a failed --no-rollback / interrupted deploy or a partially-failed automatic rollback (state-driven, no synth needed).").argument("[stack]", "Stack name to roll back (defaults to the single journaled stack)").addOption(new Option("--force", "Skip the confirmation prompt").default(false)).addOption(new Option("--orphan <logicalId>", "Skip the given resource during replay (repeatable). Mirrors cdk rollback --orphan.").argParser((value, previous) => [...previous ?? [], value])).addOption(new Option("--revert-failed", "Also attempt to revert the resource whose operation FAILED mid-deploy. Off by default: the remote state of the failed resource is unknown, so force-applying its previous state is opt-in.").default(false)).addOption(new Option("--drop-failed <logicalId>", "Remove ONE journaled failed CREATE (a resource cdkd proved it made, journaled as its only record) from the rollback journal, after checking that resource by hand. Replays nothing and deletes nothing in AWS; every other entry is kept.")).addOption(skipFinalSnapshotOption).addOption(new Option("--remove-protection", `Turn deletion protection off before this stack's rollback deletes a resource the failed deploy left: one its state records from a completed CREATE, or one a failed CREATE left behind (a journaled orphan, or under --revert-failed the failed CREATE itself) when cdkd can prove it is that resource and no other stack holds it. A nested stack it deletes cascades the flag to that child's resources, and a nested stack it reverts carries it into that child's revert. Covers ${removeProtectionTypeList()}.`).default(false)).addOption(stackRegionOption()).addHelpText("after", [
|
|
21034
|
+
const cmd = new Command("rollback").description("Revert a stack to its pre-deploy state after a failed --no-rollback / interrupted deploy or a partially-failed automatic rollback (state-driven, no synth needed).").argument("[stack]", "Stack name to roll back (defaults to the single journaled stack)").addOption(new Option("--force", "Skip the confirmation prompt").default(false)).addOption(new Option("--orphan <logicalId>", "Skip the given resource during replay (repeatable). Mirrors cdk rollback --orphan.").argParser((value, previous) => [...previous ?? [], value])).addOption(new Option("--revert-failed", "Also attempt to revert the resource whose operation FAILED mid-deploy. Off by default: the remote state of the failed resource is unknown, so force-applying its previous state is opt-in.").default(false)).addOption(new Option("--drop-failed <logicalId>", "Remove ONE journaled failed CREATE (a resource cdkd proved it made, journaled as its only record) from the rollback journal, after checking that resource by hand. Replays nothing and deletes nothing in AWS; every other entry is kept.")).addOption(skipFinalSnapshotOption).addOption(noLocalCustomResourcesOption).addOption(new Option("--remove-protection", `Turn deletion protection off before this stack's rollback deletes a resource the failed deploy left: one its state records from a completed CREATE, or one a failed CREATE left behind (a journaled orphan, or under --revert-failed the failed CREATE itself) when cdkd can prove it is that resource and no other stack holds it. A nested stack it deletes cascades the flag to that child's resources, and a nested stack it reverts carries it into that child's revert. Covers ${removeProtectionTypeList()}.`).default(false)).addOption(stackRegionOption()).addHelpText("after", [
|
|
21623
21035
|
"",
|
|
21624
21036
|
"Examples:",
|
|
21625
21037
|
" cdkd rollback MyStack",
|
|
@@ -23514,6 +22926,8 @@ async function refactorCommand(stacks, options) {
|
|
|
23514
22926
|
}
|
|
23515
22927
|
const plans = [];
|
|
23516
22928
|
const planStacks = /* @__PURE__ */ new Map();
|
|
22929
|
+
const noEchoMacCache = /* @__PURE__ */ new Map();
|
|
22930
|
+
const macWriteOnlyLookups = /* @__PURE__ */ new Map();
|
|
23517
22931
|
for (const stackInfo of targetStacks) {
|
|
23518
22932
|
const stackRegion = await regionForStack(stackInfo.stackName, stackInfo.region);
|
|
23519
22933
|
const stateData = await stateBackend.getState(stackInfo.stackName, stackRegion);
|
|
@@ -23532,6 +22946,8 @@ async function refactorCommand(stacks, options) {
|
|
|
23532
22946
|
...options.cfnFallback === false && { cfnFallback: false },
|
|
23533
22947
|
producerLookup,
|
|
23534
22948
|
...stackInfo.account && { consumerAccount: stackInfo.account },
|
|
22949
|
+
noEchoMacCache,
|
|
22950
|
+
macWriteOnlyLookups,
|
|
23535
22951
|
refusalRecovery: recovery,
|
|
23536
22952
|
inheritSecretBearingTemplate: false,
|
|
23537
22953
|
previewMaskedInputs: true,
|
|
@@ -24891,7 +24307,7 @@ function buildStackState(stackName, region, rows, templateParser, template, exis
|
|
|
24891
24307
|
}
|
|
24892
24308
|
if (namesParameter?.failedClosed !== void 0) getLogger().debug(`The template's parameter dependence could not be judged (${namesParameter.failedClosed}): every prior observed-baseline refusal recorded without a reason is carried as an unverifiable-parameter refusal.`);
|
|
24893
24309
|
return {
|
|
24894
|
-
version:
|
|
24310
|
+
version: 17,
|
|
24895
24311
|
stackName,
|
|
24896
24312
|
region,
|
|
24897
24313
|
resources,
|
|
@@ -25236,7 +24652,6 @@ async function importCommand(stackArg, options) {
|
|
|
25236
24652
|
const effectiveRegion = await resolveEffectiveRegion(options);
|
|
25237
24653
|
exportInferredRegionForSdk(effectiveRegion);
|
|
25238
24654
|
const region = effectiveRegion.region;
|
|
25239
|
-
const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
|
|
25240
24655
|
if (options.region) {
|
|
25241
24656
|
process.env["AWS_REGION"] = options.region;
|
|
25242
24657
|
process.env["AWS_DEFAULT_REGION"] = options.region;
|
|
@@ -25248,6 +24663,13 @@ async function importCommand(stackArg, options) {
|
|
|
25248
24663
|
setAwsClients(awsClients);
|
|
25249
24664
|
let targetClients;
|
|
25250
24665
|
try {
|
|
24666
|
+
if (!options.dryRun) await ensureAwsEmulatorStateBucket({
|
|
24667
|
+
cliBucket: options.stateBucket,
|
|
24668
|
+
region,
|
|
24669
|
+
s3: awsClients.s3,
|
|
24670
|
+
sts: awsClients.sts
|
|
24671
|
+
});
|
|
24672
|
+
const stateBucket = await resolveStateBucketWithDefault(options.stateBucket, region, legacyStateBucketFallbackRegion(effectiveRegion));
|
|
25251
24673
|
const stateConfig = {
|
|
25252
24674
|
bucket: stateBucket,
|
|
25253
24675
|
prefix: options.statePrefix
|
|
@@ -25452,6 +24874,16 @@ function collectMultiple(value, previous) {
|
|
|
25452
24874
|
return [...previous ?? [], value];
|
|
25453
24875
|
}
|
|
25454
24876
|
|
|
24877
|
+
// src/cli/options/emulate-role-via.ts
|
|
24878
|
+
function checkEmulateRoleVia(value, args) {
|
|
24879
|
+
if (value === void 0) return;
|
|
24880
|
+
assertFlagRoleArn("--emulate-role-via", value);
|
|
24881
|
+
if (!args.roleRequested) getLogger().warn(safeMsg`--emulate-role-via has no effect without ${args.roleFlag}: it is used only when that flag's AssumeRole is refused.`);
|
|
24882
|
+
}
|
|
24883
|
+
function emulateRoleViaOption(roleFlag) {
|
|
24884
|
+
return new Option("--emulate-role-via <arn>", `When the ${roleFlag} AssumeRole is refused (the role does not trust you), cdkd emulates the role's permissions: it assumes THIS role with the execution role's policies as session policies, so only what both allow is allowed. For callers that are not an IAM user (IAM Identity Center, a role session); an IAM user gets the same through sts:GetFederationToken without this flag. An approximation: resource-based policies, key policies and conditions naming the role, and its permissions boundary, are not reproduced.`);
|
|
24885
|
+
}
|
|
24886
|
+
|
|
25455
24887
|
// src/utils/local-aws-failure.ts
|
|
25456
24888
|
function describeLocalAwsFailureForWarn(err, operation) {
|
|
25457
24889
|
if (err instanceof CdkdError) return withoutTrailingPeriod(displaySafe(err.message));
|
|
@@ -25886,334 +25318,6 @@ function createLocalStateProvider$1(options, cdkdStackName, synthRegion, behavio
|
|
|
25886
25318
|
return createLocalStateProvider(options, cdkdStackName, synthRegion, cdkdExtraStateProviders, behavior);
|
|
25887
25319
|
}
|
|
25888
25320
|
|
|
25889
|
-
// src/local/docker-runner.ts
|
|
25890
|
-
const execFileAsync$7 = promisify(execFile);
|
|
25891
|
-
var DockerRunnerError = class DockerRunnerError extends Error {
|
|
25892
|
-
constructor(message) {
|
|
25893
|
-
super(message);
|
|
25894
|
-
this.name = "DockerRunnerError";
|
|
25895
|
-
Object.setPrototypeOf(this, DockerRunnerError.prototype);
|
|
25896
|
-
}
|
|
25897
|
-
};
|
|
25898
|
-
async function pullImage(image, skipPull) {
|
|
25899
|
-
const logger = getLogger().child("docker");
|
|
25900
|
-
if (skipPull) {
|
|
25901
|
-
logger.debug(`Skipping docker pull for ${image} (--no-pull)`);
|
|
25902
|
-
return;
|
|
25903
|
-
}
|
|
25904
|
-
if (getLogger().getLevel() === "debug") {
|
|
25905
|
-
logger.info(`Pulling ${image}...`);
|
|
25906
|
-
try {
|
|
25907
|
-
await runDockerForeground(["pull", image]);
|
|
25908
|
-
} catch (err) {
|
|
25909
|
-
throw new DockerRunnerError(`docker pull ${image} failed: ${describeDockerFailure(err, ["pull", image])}`);
|
|
25910
|
-
}
|
|
25911
|
-
return;
|
|
25912
|
-
}
|
|
25913
|
-
logger.debug(`Pulling ${image} (silent — pass --verbose to stream progress)`);
|
|
25914
|
-
try {
|
|
25915
|
-
await runDockerStreaming(["pull", image], { streamLive: false });
|
|
25916
|
-
} catch (err) {
|
|
25917
|
-
const e = err;
|
|
25918
|
-
if (e.exitCode === void 0 || e.exitCode === null) throw new DockerRunnerError(`docker pull ${image} failed: ${describeDockerFailure(err, ["pull", image])}`);
|
|
25919
|
-
const detail = describeDockerCapturedOutput(err, ["pull", image], "(no output)");
|
|
25920
|
-
throw new DockerRunnerError(`docker pull ${image} exited with code ${e.exitCode}: ${detail}`);
|
|
25921
|
-
}
|
|
25922
|
-
}
|
|
25923
|
-
async function runDetached(opts) {
|
|
25924
|
-
const wiring = getActiveWorkloadAwsWiring$1();
|
|
25925
|
-
if (!wiring) return runDetachedContainer(opts);
|
|
25926
|
-
const wired = await applyLocalAwsWiring(wiring, opts.env, opts.extraMounts ?? [], opts.mounts.map((m) => m.containerPath));
|
|
25927
|
-
if (opts.network === "host" && wiring.sidecar?.passthrough && wired.env["AWS_ENDPOINT_URL_SQS"] === wiring.sidecar.endpoint) delete wired.env["AWS_ENDPOINT_URL_SQS"];
|
|
25928
|
-
const wiredOpts = {
|
|
25929
|
-
...opts,
|
|
25930
|
-
env: wired.env,
|
|
25931
|
-
extraMounts: wired.extraMounts
|
|
25932
|
-
};
|
|
25933
|
-
const ports = loopbackPortsFor(wiring, wired.env, opts.network);
|
|
25934
|
-
if (ports.length > 0) await prepareLocalLoopbackForwarder(wiring);
|
|
25935
|
-
const id = await runDetachedContainer(wiredOpts);
|
|
25936
|
-
await attachLocalLoopbackForwarder(id, ports);
|
|
25937
|
-
return id;
|
|
25938
|
-
}
|
|
25939
|
-
async function runDetachedContainer(opts) {
|
|
25940
|
-
const args = [
|
|
25941
|
-
"run",
|
|
25942
|
-
"-d",
|
|
25943
|
-
"--rm"
|
|
25944
|
-
];
|
|
25945
|
-
if (opts.name) args.push("--name", opts.name);
|
|
25946
|
-
if (opts.network) args.push("--network", opts.network);
|
|
25947
|
-
if (opts.platform) args.push("--platform", opts.platform);
|
|
25948
|
-
if (opts.extraHosts) for (const entry of opts.extraHosts) args.push("--add-host", `${entry.host}:${entry.ip}`);
|
|
25949
|
-
const host = opts.host ?? "127.0.0.1";
|
|
25950
|
-
args.push("-p", `${host}:${opts.hostPort}:${opts.containerPort ?? 8080}`);
|
|
25951
|
-
if (opts.debugPort !== void 0) args.push("-p", `${host}:${opts.debugPort}:${opts.debugPort}`);
|
|
25952
|
-
for (const mount of opts.mounts) {
|
|
25953
|
-
const ro = mount.readOnly ? ":ro" : "";
|
|
25954
|
-
args.push("-v", `${mount.hostPath}:${mount.containerPath}${ro}`);
|
|
25955
|
-
}
|
|
25956
|
-
if (opts.extraMounts) for (const mount of opts.extraMounts) {
|
|
25957
|
-
const ro = mount.readOnly ? ":ro" : "";
|
|
25958
|
-
args.push("-v", `${mount.hostPath}:${mount.containerPath}${ro}`);
|
|
25959
|
-
}
|
|
25960
|
-
const sensitiveKeys = opts.sensitiveEnvKeys && opts.sensitiveEnvKeys.size > 0 ? /* @__PURE__ */ new Set([...SENSITIVE_ENV_KEYS, ...opts.sensitiveEnvKeys]) : SENSITIVE_ENV_KEYS;
|
|
25961
|
-
const { flags, sensitiveEnv: passthroughEnv, collisions } = partitionSensitiveEnv(opts.env, sensitiveKeys, { ...opts.name !== void 0 && { subject: `Container '${opts.name}'` } });
|
|
25962
|
-
args.push(...flags);
|
|
25963
|
-
if (opts.tmpfs) args.push("--tmpfs", `${opts.tmpfs.target}:rw,size=${opts.tmpfs.sizeMb}m`);
|
|
25964
|
-
if (opts.workingDir) args.push("--workdir", opts.workingDir);
|
|
25965
|
-
let entryPointTail = [];
|
|
25966
|
-
if (opts.entryPoint && opts.entryPoint.length > 0) {
|
|
25967
|
-
args.push("--entrypoint", opts.entryPoint[0]);
|
|
25968
|
-
entryPointTail = opts.entryPoint.slice(1);
|
|
25969
|
-
}
|
|
25970
|
-
args.push(opts.image, ...entryPointTail, ...opts.cmd);
|
|
25971
|
-
const logger = getLogger().child("docker");
|
|
25972
|
-
logger.debug(`${getDockerCmd()} ${redactDockerArgvValues(args).join(" ")}`);
|
|
25973
|
-
if (collisions.length > 0) logger.warn(`Env var(s) ${collisions.map((k) => JSON.stringify(k)).join(", ")} share a name with a variable the container client reads (docker, or the CDK_DOCKER binary) or have a malformed name (empty, or containing '=' / NUL), and were NOT passed to the container at all (a colliding name would hijack that client; a malformed name cannot form a valid environment variable). Rename the env var if the container needs it.`);
|
|
25974
|
-
const forwardedKeys = Object.keys(passthroughEnv);
|
|
25975
|
-
const refusal = finchSecretArgvRefusal(forwardedKeys.filter((k) => opts.sensitiveEnvKeys?.has(k)), `Container for image ${displayIdent(opts.image)}`);
|
|
25976
|
-
if (refusal !== void 0) throw new DockerRunnerError(refusal);
|
|
25977
|
-
warnFinchArgvExposure(forwardedKeys);
|
|
25978
|
-
try {
|
|
25979
|
-
const { stdout } = await execFileAsync$7(getDockerCmd(), args, {
|
|
25980
|
-
maxBuffer: 10485760,
|
|
25981
|
-
env: dockerSpawnEnvWithSensitive(passthroughEnv)
|
|
25982
|
-
});
|
|
25983
|
-
return stdout.trim();
|
|
25984
|
-
} catch (error) {
|
|
25985
|
-
throw new DockerRunnerError(`docker run failed: ${describeDockerFailure(error, args)}`);
|
|
25986
|
-
}
|
|
25987
|
-
}
|
|
25988
|
-
function streamLogs(containerId) {
|
|
25989
|
-
const stream = followContainerLogs(containerId);
|
|
25990
|
-
return () => stream.stop();
|
|
25991
|
-
}
|
|
25992
|
-
const RESERVATION_ROUTED_SINKS = {
|
|
25993
|
-
stdout: (chunk) => {
|
|
25994
|
-
if (isStdoutReservedForPayload()) process.stderr.write(chunk);
|
|
25995
|
-
else process.stdout.write(chunk);
|
|
25996
|
-
},
|
|
25997
|
-
stderr: (chunk) => {
|
|
25998
|
-
process.stderr.write(chunk);
|
|
25999
|
-
}
|
|
26000
|
-
};
|
|
26001
|
-
function followContainerLogs(containerId, sinks = RESERVATION_ROUTED_SINKS) {
|
|
26002
|
-
const proc = spawn(getDockerCmd(), [
|
|
26003
|
-
"logs",
|
|
26004
|
-
"-f",
|
|
26005
|
-
containerId
|
|
26006
|
-
], { stdio: [
|
|
26007
|
-
"ignore",
|
|
26008
|
-
"pipe",
|
|
26009
|
-
"pipe"
|
|
26010
|
-
] });
|
|
26011
|
-
proc.stdout?.on("data", (chunk) => sinks.stdout(chunk));
|
|
26012
|
-
proc.stderr?.on("data", (chunk) => sinks.stderr(chunk));
|
|
26013
|
-
let markClosed = () => void 0;
|
|
26014
|
-
const closed = new Promise((resolveClosed) => {
|
|
26015
|
-
markClosed = resolveClosed;
|
|
26016
|
-
});
|
|
26017
|
-
proc.on("close", () => markClosed());
|
|
26018
|
-
proc.on("error", () => {
|
|
26019
|
-
markClosed();
|
|
26020
|
-
});
|
|
26021
|
-
const stop = () => {
|
|
26022
|
-
if (!proc.killed) proc.kill("SIGTERM");
|
|
26023
|
-
};
|
|
26024
|
-
return {
|
|
26025
|
-
stop,
|
|
26026
|
-
drain: async (timeoutMs) => {
|
|
26027
|
-
let timer;
|
|
26028
|
-
const timedOut = new Promise((resolveTimeout) => {
|
|
26029
|
-
timer = setTimeout(() => resolveTimeout(false), timeoutMs);
|
|
26030
|
-
});
|
|
26031
|
-
try {
|
|
26032
|
-
const drained = await Promise.race([closed.then(() => true), timedOut]);
|
|
26033
|
-
if (!drained) {
|
|
26034
|
-
getLogger().child("docker").debug(safeMsg`docker logs -f ${containerId} did not end within ${timeoutMs}ms; stopping it (later log lines may be missing)`);
|
|
26035
|
-
stop();
|
|
26036
|
-
}
|
|
26037
|
-
return drained;
|
|
26038
|
-
} finally {
|
|
26039
|
-
clearTimeout(timer);
|
|
26040
|
-
}
|
|
26041
|
-
}
|
|
26042
|
-
};
|
|
26043
|
-
}
|
|
26044
|
-
async function killContainer(containerId, timeoutMs = 1e4) {
|
|
26045
|
-
if (!containerId) return;
|
|
26046
|
-
const args = ["kill", containerId];
|
|
26047
|
-
try {
|
|
26048
|
-
await execFileAsync$7(getDockerCmd(), args, { timeout: timeoutMs });
|
|
26049
|
-
} catch (error) {
|
|
26050
|
-
getLogger().child("docker").debug(safeMsg`docker kill ${containerId} failed: ${describeDockerFailure(error, args)}`);
|
|
26051
|
-
}
|
|
26052
|
-
}
|
|
26053
|
-
const CONTAINER_LOG_DRAIN_TIMEOUT_MS = 5e3;
|
|
26054
|
-
async function killAndDrainContainerLogs(containerId, stream, timeoutMs = CONTAINER_LOG_DRAIN_TIMEOUT_MS) {
|
|
26055
|
-
if (!stream) return;
|
|
26056
|
-
if (containerId) await killContainer(containerId);
|
|
26057
|
-
await stream.drain(timeoutMs);
|
|
26058
|
-
}
|
|
26059
|
-
async function flushStdio(timeoutMs = 2e3) {
|
|
26060
|
-
const flushed = (stream) => new Promise((resolveFlush) => {
|
|
26061
|
-
try {
|
|
26062
|
-
stream.write("", () => resolveFlush());
|
|
26063
|
-
} catch {
|
|
26064
|
-
resolveFlush();
|
|
26065
|
-
}
|
|
26066
|
-
});
|
|
26067
|
-
let timer;
|
|
26068
|
-
await Promise.race([Promise.all([flushed(process.stdout), flushed(process.stderr)]), new Promise((resolveTimeout) => {
|
|
26069
|
-
timer = setTimeout(resolveTimeout, timeoutMs);
|
|
26070
|
-
})]);
|
|
26071
|
-
clearTimeout(timer);
|
|
26072
|
-
}
|
|
26073
|
-
async function removeContainer(containerId) {
|
|
26074
|
-
if (!containerId) return;
|
|
26075
|
-
const logger = getLogger().child("docker");
|
|
26076
|
-
const args = [
|
|
26077
|
-
"rm",
|
|
26078
|
-
"-f",
|
|
26079
|
-
containerId
|
|
26080
|
-
];
|
|
26081
|
-
try {
|
|
26082
|
-
await execFileAsync$7(getDockerCmd(), args);
|
|
26083
|
-
logger.debug(`Removed container ${containerId}`);
|
|
26084
|
-
} catch (error) {
|
|
26085
|
-
logger.debug(`docker rm -f ${containerId} failed: ${describeDockerFailure(error, args)}`);
|
|
26086
|
-
}
|
|
26087
|
-
}
|
|
26088
|
-
async function ensureDockerAvailable() {
|
|
26089
|
-
const cmd = getDockerCmd();
|
|
26090
|
-
const args = [
|
|
26091
|
-
"version",
|
|
26092
|
-
"--format",
|
|
26093
|
-
"{{.Server.Version}}"
|
|
26094
|
-
];
|
|
26095
|
-
try {
|
|
26096
|
-
await execFileAsync$7(cmd, args);
|
|
26097
|
-
} catch (error) {
|
|
26098
|
-
if (error.code === "ENOENT") throw new DockerRunnerError(`${cmd} is not installed or not on PATH. cdkd local invoke needs Docker (or a compatible CLI specified via CDK_DOCKER) — install it and retry.`);
|
|
26099
|
-
throw new DockerRunnerError(`${cmd} daemon is not reachable: ${describeDockerFailure(error, args)}. Start Docker Desktop / the docker daemon and retry.`);
|
|
26100
|
-
}
|
|
26101
|
-
}
|
|
26102
|
-
function pickFreePort() {
|
|
26103
|
-
return new Promise((resolvePort, rejectPort) => {
|
|
26104
|
-
const server = createServer();
|
|
26105
|
-
server.unref();
|
|
26106
|
-
server.on("error", rejectPort);
|
|
26107
|
-
server.listen(0, "127.0.0.1", () => {
|
|
26108
|
-
const address = server.address();
|
|
26109
|
-
if (!address || typeof address === "string") {
|
|
26110
|
-
server.close();
|
|
26111
|
-
rejectPort(/* @__PURE__ */ new Error("Could not allocate a host port"));
|
|
26112
|
-
return;
|
|
26113
|
-
}
|
|
26114
|
-
const port = address.port;
|
|
26115
|
-
server.close(() => resolvePort(port));
|
|
26116
|
-
});
|
|
26117
|
-
});
|
|
26118
|
-
}
|
|
26119
|
-
const SENSITIVE_ENV_KEYS = /* @__PURE__ */ new Set([
|
|
26120
|
-
"AWS_ACCESS_KEY_ID",
|
|
26121
|
-
"AWS_SECRET_ACCESS_KEY",
|
|
26122
|
-
"AWS_SESSION_TOKEN"
|
|
26123
|
-
]);
|
|
26124
|
-
|
|
26125
|
-
// src/local/rie-client.ts
|
|
26126
|
-
const INVOKE_PATH = "/2015-03-31/functions/function/invocations";
|
|
26127
|
-
const NOT_AN_RIE_STATUS = /* @__PURE__ */ new Set([404, 405]);
|
|
26128
|
-
async function waitForRieReady(host, port, timeoutMs = 5e3) {
|
|
26129
|
-
const deadline = Date.now() + timeoutMs;
|
|
26130
|
-
let lastError;
|
|
26131
|
-
while (Date.now() < deadline) {
|
|
26132
|
-
try {
|
|
26133
|
-
if (await httpProbe(host, port, 500)) {
|
|
26134
|
-
await setTimeout$1(250);
|
|
26135
|
-
return;
|
|
26136
|
-
}
|
|
26137
|
-
} catch (err) {
|
|
26138
|
-
lastError = err;
|
|
26139
|
-
}
|
|
26140
|
-
await setTimeout$1(100);
|
|
26141
|
-
}
|
|
26142
|
-
const tail = lastError instanceof Error ? `: ${lastError.message}` : "";
|
|
26143
|
-
throw new Error(`RIE did not become ready on ${host} port ${port} within ${timeoutMs}ms${tail}. The container may have exited early — check 'docker logs' output.`);
|
|
26144
|
-
}
|
|
26145
|
-
async function httpProbe(host, port, timeoutMs) {
|
|
26146
|
-
const controller = new AbortController();
|
|
26147
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
26148
|
-
try {
|
|
26149
|
-
await (await fetch(`http://${formatAuthority(host, port)}/`, {
|
|
26150
|
-
method: "POST",
|
|
26151
|
-
headers: { "Content-Type": "application/json" },
|
|
26152
|
-
body: "{}",
|
|
26153
|
-
signal: controller.signal
|
|
26154
|
-
})).text().catch(() => void 0);
|
|
26155
|
-
return true;
|
|
26156
|
-
} catch (err) {
|
|
26157
|
-
if (isTransientNetworkError(err)) return false;
|
|
26158
|
-
throw err;
|
|
26159
|
-
} finally {
|
|
26160
|
-
clearTimeout(timer);
|
|
26161
|
-
}
|
|
26162
|
-
}
|
|
26163
|
-
function isTransientNetworkError(err) {
|
|
26164
|
-
if (!(err instanceof Error)) return false;
|
|
26165
|
-
if (err.name === "AbortError") return true;
|
|
26166
|
-
if (err.name === "TypeError" && err.message === "fetch failed") return true;
|
|
26167
|
-
const cause = err.cause;
|
|
26168
|
-
if (cause?.code === "ECONNRESET") return true;
|
|
26169
|
-
if (cause?.code === "ECONNREFUSED") return true;
|
|
26170
|
-
if (cause?.code === "UND_ERR_SOCKET") return true;
|
|
26171
|
-
return false;
|
|
26172
|
-
}
|
|
26173
|
-
async function invokeRie(host, port, event, timeoutMs) {
|
|
26174
|
-
const url = `http://${formatAuthority(host, port)}${INVOKE_PATH}`;
|
|
26175
|
-
const body = JSON.stringify(event ?? {});
|
|
26176
|
-
const controller = new AbortController();
|
|
26177
|
-
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
26178
|
-
let response;
|
|
26179
|
-
try {
|
|
26180
|
-
response = await fetchWithStartupRetry(url, body, controller.signal);
|
|
26181
|
-
} catch (err) {
|
|
26182
|
-
if (err.name === "AbortError") throw new Error(`RIE invoke at ${url} timed out after ${timeoutMs}ms. The handler may be hung; check container logs.`);
|
|
26183
|
-
throw err;
|
|
26184
|
-
} finally {
|
|
26185
|
-
clearTimeout(timer);
|
|
26186
|
-
}
|
|
26187
|
-
const raw = await response.text();
|
|
26188
|
-
if (NOT_AN_RIE_STATUS.has(response.status)) throw new Error(`The container answered the invoke at ${url} with HTTP ${response.status}, which the Lambda Runtime Interface Emulator never sends for that path: something else is listening on the container's port 8080 (the function's own server?). Check the container logs.`);
|
|
26189
|
-
let payload = raw;
|
|
26190
|
-
try {
|
|
26191
|
-
payload = JSON.parse(raw);
|
|
26192
|
-
} catch {}
|
|
26193
|
-
return {
|
|
26194
|
-
payload,
|
|
26195
|
-
raw
|
|
26196
|
-
};
|
|
26197
|
-
}
|
|
26198
|
-
async function fetchWithStartupRetry(url, body, signal) {
|
|
26199
|
-
const maxAttempts = 3;
|
|
26200
|
-
let lastError;
|
|
26201
|
-
for (let attempt = 1; attempt <= maxAttempts; attempt++) try {
|
|
26202
|
-
return await fetch(url, {
|
|
26203
|
-
method: "POST",
|
|
26204
|
-
headers: { "Content-Type": "application/json" },
|
|
26205
|
-
body,
|
|
26206
|
-
signal
|
|
26207
|
-
});
|
|
26208
|
-
} catch (err) {
|
|
26209
|
-
if (err.name === "AbortError") throw err;
|
|
26210
|
-
lastError = err;
|
|
26211
|
-
if (attempt === maxAttempts) break;
|
|
26212
|
-
await setTimeout$1(200);
|
|
26213
|
-
}
|
|
26214
|
-
throw lastError;
|
|
26215
|
-
}
|
|
26216
|
-
|
|
26217
25321
|
// src/local/container-pool.ts
|
|
26218
25322
|
const DEFAULT_IDLE_MS = 6e4;
|
|
26219
25323
|
const IN_FLIGHT_START_TIMEOUT_MS = 2e4;
|
|
@@ -27460,53 +26564,6 @@ function createCallerDynamicReferenceResolver(profile) {
|
|
|
27460
26564
|
});
|
|
27461
26565
|
}
|
|
27462
26566
|
|
|
27463
|
-
// src/local/layer-tree-copy.ts
|
|
27464
|
-
function copyLayerTreeLastWins(src, dest) {
|
|
27465
|
-
mkdirSync(dest, { recursive: true });
|
|
27466
|
-
copyDirLastWins(realpathSync.native(src), dest);
|
|
27467
|
-
}
|
|
27468
|
-
function copyDirLastWins(fromDir, toDir) {
|
|
27469
|
-
for (const entry of readdirSync(fromDir, { withFileTypes: true })) {
|
|
27470
|
-
const from = join(fromDir, entry.name);
|
|
27471
|
-
const to = join(toDir, entry.name);
|
|
27472
|
-
if (entry.isSymbolicLink()) {
|
|
27473
|
-
removeUnless(to, "symlink");
|
|
27474
|
-
symlinkSync(readlinkSync(from), to);
|
|
27475
|
-
} else if (entry.isDirectory()) {
|
|
27476
|
-
removeUnless(to, "directory");
|
|
27477
|
-
mkdirSync(to, { recursive: true });
|
|
27478
|
-
copyDirLastWins(from, to);
|
|
27479
|
-
} else {
|
|
27480
|
-
removeUnless(to, "file");
|
|
27481
|
-
cpSync(from, to, { force: true });
|
|
27482
|
-
}
|
|
27483
|
-
}
|
|
27484
|
-
}
|
|
27485
|
-
function removeUnless(to, kind) {
|
|
27486
|
-
let st;
|
|
27487
|
-
try {
|
|
27488
|
-
st = lstatSync(to);
|
|
27489
|
-
} catch {
|
|
27490
|
-
return;
|
|
27491
|
-
}
|
|
27492
|
-
if (kind === "directory" && st.isDirectory()) return;
|
|
27493
|
-
if (kind === "file" && st.isFile()) return;
|
|
27494
|
-
rmSync(to, {
|
|
27495
|
-
recursive: true,
|
|
27496
|
-
force: true
|
|
27497
|
-
});
|
|
27498
|
-
}
|
|
27499
|
-
|
|
27500
|
-
// src/local/docker-image-builder.ts
|
|
27501
|
-
async function buildContainerImage$1(asset, cdkOutDir, options) {
|
|
27502
|
-
try {
|
|
27503
|
-
return await buildContainerImage(asset, cdkOutDir, options);
|
|
27504
|
-
} catch (e) {
|
|
27505
|
-
if (e instanceof LocalInvokeBuildError) throw new LocalInvokeBuildError$1(e.message);
|
|
27506
|
-
throw e;
|
|
27507
|
-
}
|
|
27508
|
-
}
|
|
27509
|
-
|
|
27510
26567
|
// src/local/ecr-puller.ts
|
|
27511
26568
|
function canonicalizeImageUriHost(imageUri) {
|
|
27512
26569
|
const slash = imageUri.indexOf("/");
|
|
@@ -27542,6 +26599,7 @@ function isCredentialFresh(creds) {
|
|
|
27542
26599
|
if (!creds.expiration) return false;
|
|
27543
26600
|
return creds.expiration.getTime() - Date.now() > STS_CREDENTIAL_SAFETY_MARGIN_MS;
|
|
27544
26601
|
}
|
|
26602
|
+
const ECR_EMULATOR_REFUSAL = (image) => `--aws-emulator: image ${image} is in a real ECR registry, and ECR is not excepted to real AWS for this workload, so it is not pulled (AWS Emulator serves no registry docker can pull from). To pull it from real ECR with your real identity, except ECR for the workload in the --env-vars file ("AWS_ENDPOINT_URL_ECR": "real-aws", under "Parameters" or the workload's own section); or pull the image yourself and pass --no-pull.`;
|
|
27545
26603
|
async function pullEcrImage(imageUri, options) {
|
|
27546
26604
|
if (realAwsException("ECR", options.workload)) return runWithRealAws(() => pullEcrImageOnSide(imageUri, options, "real"));
|
|
27547
26605
|
return pullEcrImageOnSide(imageUri, options, "default");
|
|
@@ -27557,6 +26615,7 @@ async function pullEcrImageOnSide(imageUri, options, side) {
|
|
|
27557
26615
|
await verifyImageInLocalCache(canonicalUri);
|
|
27558
26616
|
return canonicalUri;
|
|
27559
26617
|
}
|
|
26618
|
+
if (side === "default" && isAwsServiceRoutedToEmulator("ECR", options.workload)) throw new LocalInvokeBuildError$1(ECR_EMULATOR_REFUSAL(displayIdent(canonicalUri)));
|
|
27560
26619
|
const credentialConfig = ambientCredentialConfig();
|
|
27561
26620
|
const identityFingerprint = injectiveKey(side, credentialFingerprint(credentialConfig));
|
|
27562
26621
|
const callerIdentityKey = injectiveKey(identityFingerprint, callerRegion ?? "_unset");
|
|
@@ -27605,8 +26664,9 @@ async function pullEcrImageOnSide(imageUri, options, side) {
|
|
|
27605
26664
|
region: parsed.region,
|
|
27606
26665
|
...assumed && { credentials: assumed }
|
|
27607
26666
|
});
|
|
26667
|
+
const dockerEnv = dockerRegistryEnv(options.workload);
|
|
27608
26668
|
try {
|
|
27609
|
-
await ecrLogin(ecr, {
|
|
26669
|
+
await ecrLogin(ecr, dockerEnv, {
|
|
27610
26670
|
accountId: parsed.accountId,
|
|
27611
26671
|
region: parsed.region,
|
|
27612
26672
|
registryHost: canonicalUri.slice(0, canonicalUri.indexOf("/"))
|
|
@@ -27617,7 +26677,7 @@ async function pullEcrImageOnSide(imageUri, options, side) {
|
|
|
27617
26677
|
logger.info(`Pulling ${canonicalUri}...`);
|
|
27618
26678
|
const pullArgs = ["pull", canonicalUri];
|
|
27619
26679
|
try {
|
|
27620
|
-
await runDockerForeground(pullArgs);
|
|
26680
|
+
await runDockerForeground(pullArgs, { env: dockerEnv });
|
|
27621
26681
|
} catch (err) {
|
|
27622
26682
|
throw new LocalInvokeBuildError$1(`docker pull ${canonicalUri} failed: ${describeDockerFailure(err, pullArgs)}`, redactedDockerCause(err, pullArgs));
|
|
27623
26683
|
}
|
|
@@ -27651,7 +26711,7 @@ async function assumeRoleForEcr(roleArn, callerRegion, credentialConfig, logger)
|
|
|
27651
26711
|
sts.destroy();
|
|
27652
26712
|
}
|
|
27653
26713
|
}
|
|
27654
|
-
async function ecrLogin(client, target) {
|
|
26714
|
+
async function ecrLogin(client, dockerEnv, target) {
|
|
27655
26715
|
const { accountId, region, registryHost } = target;
|
|
27656
26716
|
getLogger().child("ecr-puller").debug(`ECR login (account=${accountId}, region=${region}, host=${registryHost})`);
|
|
27657
26717
|
let response;
|
|
@@ -27674,7 +26734,10 @@ async function ecrLogin(client, target) {
|
|
|
27674
26734
|
endpoint
|
|
27675
26735
|
];
|
|
27676
26736
|
try {
|
|
27677
|
-
await runDockerStreaming(loginArgs, {
|
|
26737
|
+
await runDockerStreaming(loginArgs, {
|
|
26738
|
+
input: password,
|
|
26739
|
+
env: dockerEnv
|
|
26740
|
+
});
|
|
27678
26741
|
} catch (err) {
|
|
27679
26742
|
throw new LocalInvokeBuildError$1(`ECR login failed: ${formatDockerLoginError(describeDockerFailure(err, loginArgs), endpoint)}`, redactedDockerCause(err, loginArgs));
|
|
27680
26743
|
}
|
|
@@ -27877,337 +26940,6 @@ async function extractRie(platform, target, machine, skipPull) {
|
|
|
27877
26940
|
}
|
|
27878
26941
|
}
|
|
27879
26942
|
|
|
27880
|
-
// src/local/lambda-resolver/types.ts
|
|
27881
|
-
var LocalInvokeResolutionError = class LocalInvokeResolutionError extends Error {
|
|
27882
|
-
constructor(message) {
|
|
27883
|
-
super(message);
|
|
27884
|
-
this.name = "LocalInvokeResolutionError";
|
|
27885
|
-
Object.setPrototypeOf(this, LocalInvokeResolutionError.prototype);
|
|
27886
|
-
}
|
|
27887
|
-
};
|
|
27888
|
-
|
|
27889
|
-
// src/local/intrinsic-image.ts
|
|
27890
|
-
function derivePseudoParametersFromRegion$1(region, accountId) {
|
|
27891
|
-
return derivePseudoParametersFromRegion(canonicalizeRegion(region), accountId);
|
|
27892
|
-
}
|
|
27893
|
-
|
|
27894
|
-
// src/local/lambda-resolver/asset-code.ts
|
|
27895
|
-
function resolveAssetCodeDirectory(opts) {
|
|
27896
|
-
const { manifestDir, assetPath, wrapError, assetOutdir, logicalId } = opts;
|
|
27897
|
-
if (isAbsolute(assetPath)) {
|
|
27898
|
-
const absolute = resolve(assetPath);
|
|
27899
|
-
const escape = absoluteAssemblyPathEscape(assetOutdir, absolute);
|
|
27900
|
-
if (escape !== void 0) getLogger().warn(`Lambda ${displayIdent(logicalId)} has an absolute Metadata['aws:asset:path'] pointing outside the assembly: ${displayAssemblyPath(absolute)}` + (escape.escape === "symlink" ? ` (through a symbolic link to ${displayAssemblyPath(escape.realPath)})` : "") + ". cdkd will bind-mount that directory into the container read-only, where the code in this assembly can read it. This is what cdk synth --no-staging emits, and is expected for it; if you did not synthesize with that flag, treat this assembly as untrusted.");
|
|
27901
|
-
return absolute;
|
|
27902
|
-
}
|
|
27903
|
-
const resolved = resolveAssemblyPath(manifestDir, assetPath, { containWithin: assetOutdir });
|
|
27904
|
-
if (!resolved.contained && resolved.escape === "lexical" && resolved.path === resolve(assetOutdir)) return resolved.path;
|
|
27905
|
-
if (!resolved.contained) throw wrapError(`Lambda ${displayIdent(logicalId)} has Metadata['aws:asset:path']=${displayAssemblyPath(assetPath)} which ${renderAssemblyPathEscape(resolved, assetOutdir, "mount it")}`);
|
|
27906
|
-
return resolved.path;
|
|
27907
|
-
}
|
|
27908
|
-
function assetPathDirs(stack) {
|
|
27909
|
-
const manifestDir = stack.assetManifestPath ? dirname(stack.assetManifestPath) : stack.assetOutdir ?? process.cwd();
|
|
27910
|
-
return {
|
|
27911
|
-
manifestDir,
|
|
27912
|
-
assetOutdir: stack.assetOutdir ?? manifestDir
|
|
27913
|
-
};
|
|
27914
|
-
}
|
|
27915
|
-
function resolveAssetCodePath$1(stack, logicalId, resource) {
|
|
27916
|
-
const assetPath = resource.Metadata?.["aws:asset:path"];
|
|
27917
|
-
if (typeof assetPath !== "string" || assetPath.length === 0) throw new LocalInvokeResolutionError(`Lambda ${plainOrDescribed(logicalId, "logical id")} has no Metadata['aws:asset:path']. cdkd local invoke needs this hint to find the local asset directory. Re-synthesize the app (without \`--output '<stale-dir>'\`) and retry.`);
|
|
27918
|
-
const { manifestDir, assetOutdir } = assetPathDirs(stack);
|
|
27919
|
-
const abs = resolveAssetCodeDirectory({
|
|
27920
|
-
manifestDir,
|
|
27921
|
-
assetPath,
|
|
27922
|
-
wrapError: (message) => new LocalInvokeResolutionError(message),
|
|
27923
|
-
assetOutdir,
|
|
27924
|
-
logicalId
|
|
27925
|
-
});
|
|
27926
|
-
if (!existsSync(abs) || !statSync(abs).isDirectory()) throw new LocalInvokeResolutionError(`Lambda ${displayIdent(logicalId)} asset directory ${displayAssemblyPath(abs)} does not exist or is not a directory. Re-synthesize the app and retry.`);
|
|
27927
|
-
return abs;
|
|
27928
|
-
}
|
|
27929
|
-
|
|
27930
|
-
// src/local/lambda-resolver/layers.ts
|
|
27931
|
-
function resolveLambdaLayers(stack, logicalId, props) {
|
|
27932
|
-
const layers = props["Layers"];
|
|
27933
|
-
if (layers === void 0) return [];
|
|
27934
|
-
if (!Array.isArray(layers)) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a non-array Layers property. Expected an array of LayerVersion references.`);
|
|
27935
|
-
if (layers.length === 0) return [];
|
|
27936
|
-
const resources = stack.template.Resources ?? {};
|
|
27937
|
-
const out = [];
|
|
27938
|
-
for (let i = 0; i < layers.length; i++) {
|
|
27939
|
-
const entry = layers[i];
|
|
27940
|
-
if (typeof entry === "string") {
|
|
27941
|
-
const parsed = classifyLayerVersionArn(entry);
|
|
27942
|
-
if (!parsed.ok) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a Layers entry [${i}] cdkd cannot resolve locally: literal string '${entry}'. Expected a same-stack Ref / Fn::GetAtt to an AWS::Lambda::LayerVersion OR a literal layer-version ARN of the form arn:aws:lambda:<region>:<account>:layer:<name>:<version>.` + describeLayerArnRejection(parsed.rejection));
|
|
27943
|
-
out.push({
|
|
27944
|
-
kind: "arn",
|
|
27945
|
-
logicalId: parsed.value.arn,
|
|
27946
|
-
...parsed.value
|
|
27947
|
-
});
|
|
27948
|
-
continue;
|
|
27949
|
-
}
|
|
27950
|
-
const layerLogicalId = pickLayerLogicalId(entry);
|
|
27951
|
-
if (!layerLogicalId) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has a Layers entry [${i}] cdkd cannot resolve locally: ${describeLayerEntry(entry)}. Expected a same-stack Ref / Fn::GetAtt to an AWS::Lambda::LayerVersion OR a literal layer-version ARN of the form arn:aws:lambda:<region>:<account>:layer:<name>:<version>.`);
|
|
27952
|
-
const layerResource = resources[layerLogicalId];
|
|
27953
|
-
if (!layerResource) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' Layers entry [${i}] references '${layerLogicalId}', but no resource with that logical ID exists in stack '${stack.stackName}'.`);
|
|
27954
|
-
if (layerResource.Type !== "AWS::Lambda::LayerVersion") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' Layers entry [${i}] references '${layerLogicalId}' (${layerResource.Type}), which is not an AWS::Lambda::LayerVersion.`);
|
|
27955
|
-
const assetPath = resolveAssetCodePath$1(stack, layerLogicalId, layerResource);
|
|
27956
|
-
out.push({
|
|
27957
|
-
kind: "asset",
|
|
27958
|
-
logicalId: layerLogicalId,
|
|
27959
|
-
assetPath
|
|
27960
|
-
});
|
|
27961
|
-
}
|
|
27962
|
-
return out;
|
|
27963
|
-
}
|
|
27964
|
-
const LAYER_ARN_PATTERN = new RegExp(`^arn:([a-z][a-z0-9-]*):lambda:([a-z]{2,}(?:-[a-z]+)+-\\d+):(\\d{12}):layer:([A-Za-z0-9_-]+):(\\d+)$`);
|
|
27965
|
-
function classifyLayerVersionArn(input) {
|
|
27966
|
-
const m = LAYER_ARN_PATTERN.exec(input);
|
|
27967
|
-
if (!m) return {
|
|
27968
|
-
ok: false,
|
|
27969
|
-
rejection: { kind: "shape" }
|
|
27970
|
-
};
|
|
27971
|
-
const partition = m[1];
|
|
27972
|
-
const region = m[2];
|
|
27973
|
-
const derived = derivePartitionAndUrlSuffix(region).partition;
|
|
27974
|
-
if (derived !== partition) return {
|
|
27975
|
-
ok: false,
|
|
27976
|
-
rejection: {
|
|
27977
|
-
kind: "partition",
|
|
27978
|
-
partition,
|
|
27979
|
-
region,
|
|
27980
|
-
derived,
|
|
27981
|
-
derivedFromTable: derived !== "aws"
|
|
27982
|
-
}
|
|
27983
|
-
};
|
|
27984
|
-
return {
|
|
27985
|
-
ok: true,
|
|
27986
|
-
value: {
|
|
27987
|
-
arn: input,
|
|
27988
|
-
region,
|
|
27989
|
-
accountId: m[3],
|
|
27990
|
-
name: m[4],
|
|
27991
|
-
version: m[5]
|
|
27992
|
-
}
|
|
27993
|
-
};
|
|
27994
|
-
}
|
|
27995
|
-
function describeLayerArnRejection(rejection) {
|
|
27996
|
-
if (rejection.kind === "shape") return "";
|
|
27997
|
-
const { partition, region, derived, derivedFromTable } = rejection;
|
|
27998
|
-
const head = ` The partition '${partition}' does not match region '${region}'`;
|
|
27999
|
-
return derivedFromTable ? `${head}, which is in partition '${derived}'.` : `${head}: no partition prefix matches that region, so cdkd resolves it to the commercial partition '${derived}'.`;
|
|
28000
|
-
}
|
|
28001
|
-
function pickLayerLogicalId(entry) {
|
|
28002
|
-
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return void 0;
|
|
28003
|
-
const obj = entry;
|
|
28004
|
-
if (typeof obj["Ref"] === "string") return obj["Ref"];
|
|
28005
|
-
if ("Fn::GetAtt" in obj) {
|
|
28006
|
-
const arg = obj["Fn::GetAtt"];
|
|
28007
|
-
if (Array.isArray(arg) && typeof arg[0] === "string") return arg[0];
|
|
28008
|
-
}
|
|
28009
|
-
}
|
|
28010
|
-
function describeLayerEntry(entry) {
|
|
28011
|
-
if (typeof entry === "string") return `literal ARN '${entry}'`;
|
|
28012
|
-
if (entry === null) return "null";
|
|
28013
|
-
if (typeof entry !== "object") return stringifyValue(entry);
|
|
28014
|
-
try {
|
|
28015
|
-
const json = JSON.stringify(entry);
|
|
28016
|
-
return json.length > 120 ? json.substring(0, 117) + "..." : json;
|
|
28017
|
-
} catch {
|
|
28018
|
-
return Object.prototype.toString.call(entry);
|
|
28019
|
-
}
|
|
28020
|
-
}
|
|
28021
|
-
|
|
28022
|
-
// src/local/lambda-resolver/properties.ts
|
|
28023
|
-
function extractLambdaProperties(stack, logicalId, resource, resources) {
|
|
28024
|
-
const props = resource.Properties ?? {};
|
|
28025
|
-
const memoryMb = typeof props["MemorySize"] === "number" ? props["MemorySize"] : 128;
|
|
28026
|
-
const timeoutSec = typeof props["Timeout"] === "number" ? props["Timeout"] : 3;
|
|
28027
|
-
const ephemeralStorageMb = extractEphemeralStorageMb(props, logicalId);
|
|
28028
|
-
const code = props["Code"] ?? {};
|
|
28029
|
-
const imageUri = extractImageUri$1(code["ImageUri"], logicalId, stack.stackName, resources, stack.region);
|
|
28030
|
-
if (imageUri !== void 0) return extractImageLambdaProperties({
|
|
28031
|
-
stack,
|
|
28032
|
-
logicalId,
|
|
28033
|
-
resource,
|
|
28034
|
-
memoryMb,
|
|
28035
|
-
timeoutSec,
|
|
28036
|
-
props,
|
|
28037
|
-
imageUri,
|
|
28038
|
-
...ephemeralStorageMb !== void 0 && { ephemeralStorageMb }
|
|
28039
|
-
});
|
|
28040
|
-
const runtime = typeof props["Runtime"] === "string" ? props["Runtime"] : "";
|
|
28041
|
-
const handler = typeof props["Handler"] === "string" ? props["Handler"] : "";
|
|
28042
|
-
if (!runtime) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has no Runtime property and no Code.ImageUri. cdkd cannot tell if this is a ZIP or a container Lambda.`);
|
|
28043
|
-
if (!handler) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has no Handler property.`);
|
|
28044
|
-
const inlineCode = typeof code["ZipFile"] === "string" ? code["ZipFile"] : void 0;
|
|
28045
|
-
let codePath = null;
|
|
28046
|
-
if (!inlineCode) codePath = resolveAssetCodePath$1(stack, logicalId, resource);
|
|
28047
|
-
const layers = resolveLambdaLayers(stack, logicalId, props);
|
|
28048
|
-
return {
|
|
28049
|
-
kind: "zip",
|
|
28050
|
-
stack,
|
|
28051
|
-
logicalId,
|
|
28052
|
-
resource,
|
|
28053
|
-
runtime,
|
|
28054
|
-
handler,
|
|
28055
|
-
memoryMb,
|
|
28056
|
-
timeoutSec,
|
|
28057
|
-
architecture: extractArchitecture(props, logicalId),
|
|
28058
|
-
codePath,
|
|
28059
|
-
layers,
|
|
28060
|
-
...ephemeralStorageMb !== void 0 && { ephemeralStorageMb },
|
|
28061
|
-
...inlineCode !== void 0 && { inlineCode }
|
|
28062
|
-
};
|
|
28063
|
-
}
|
|
28064
|
-
function extractEphemeralStorageMb(props, logicalId) {
|
|
28065
|
-
const raw = props["EphemeralStorage"];
|
|
28066
|
-
if (raw === void 0 || raw === null) return void 0;
|
|
28067
|
-
if (typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
28068
|
-
const size = raw["Size"];
|
|
28069
|
-
if (typeof size !== "number") return;
|
|
28070
|
-
if (!Number.isFinite(size) || size < 1) return void 0;
|
|
28071
|
-
if (size > 10240) throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has Properties.EphemeralStorage.Size = ${size} MiB, which exceeds the AWS limit of 10240 MiB. AWS would reject the function at deploy time; cap the value to <= 10240 (10 GiB) and retry.`);
|
|
28072
|
-
return Math.floor(size);
|
|
28073
|
-
}
|
|
28074
|
-
function extractImageUri$1(value, logicalId, stackName, resources, region) {
|
|
28075
|
-
if (typeof value === "string" && value.length > 0) return value;
|
|
28076
|
-
if (value && typeof value === "object" && !Array.isArray(value)) {
|
|
28077
|
-
const obj = value;
|
|
28078
|
-
const sub = obj["Fn::Sub"];
|
|
28079
|
-
if (typeof sub === "string" && sub.length > 0) return sub;
|
|
28080
|
-
if (Array.isArray(sub) && typeof sub[0] === "string") return sub[0];
|
|
28081
|
-
if ("Fn::Join" in obj) {
|
|
28082
|
-
const pseudoParameters = derivePseudoParametersFromRegion$1(region);
|
|
28083
|
-
const joinResolved = tryResolveImageFnJoin(value, resources, pseudoParameters ? { pseudoParameters } : void 0);
|
|
28084
|
-
if (joinResolved.kind === "resolved") return joinResolved.uri;
|
|
28085
|
-
if (joinResolved.kind === "needs-state") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} references same-stack ECR repository '${joinResolved.repoLogicalId}' via Fn::Join. cdkd local invoke cannot resolve the repository URI without state — deploy the stack first (so cdkd records the repository physical id), rebuild via lambda.DockerImageCode.fromImageAsset, or pin a public image.`);
|
|
28086
|
-
if (joinResolved.kind === "unsupported-join") throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} has an unsupported Fn::Join Code.ImageUri shape: ${joinResolved.reason}. cdkd local invoke recognizes the canonical CDK 2.x lambda.DockerImageCode.fromEcr Fn::Join shape (delimiter "" with nested Fn::Select/Fn::Split over an ECR Repository Arn GetAtt + Ref to the repo).`);
|
|
28087
|
-
throw new LocalInvokeResolutionError(`Lambda '${logicalId}' in ${stackName} has an Fn::Join Code.ImageUri that cdkd local invoke cannot resolve${pseudoParameters ? " (likely ${AWS::AccountId}, which cdkd cannot derive without --from-state or STS)" : ` (cdkd could not derive AWS pseudo parameters because stack.region was undefined)`}. Workarounds: deploy first and run with --from-state, or pin a fully-literal public image URI.`);
|
|
28088
|
-
}
|
|
28089
|
-
}
|
|
28090
|
-
}
|
|
28091
|
-
function extractArchitecture(props, logicalId) {
|
|
28092
|
-
const arches = props["Architectures"];
|
|
28093
|
-
if (Array.isArray(arches) && arches.length > 0) {
|
|
28094
|
-
const first = arches[0];
|
|
28095
|
-
if (first === "arm64") return "arm64";
|
|
28096
|
-
if (first === "x86_64") return "x86_64";
|
|
28097
|
-
throw new LocalInvokeResolutionError(`Lambda '${logicalId}' has unsupported Architectures value '${String(first)}'. cdkd local invoke supports x86_64 and arm64.`);
|
|
28098
|
-
}
|
|
28099
|
-
return "x86_64";
|
|
28100
|
-
}
|
|
28101
|
-
function extractImageLambdaProperties(args) {
|
|
28102
|
-
const { stack, logicalId, resource, memoryMb, timeoutSec, ephemeralStorageMb, props, imageUri } = args;
|
|
28103
|
-
const rawImageConfig = props["ImageConfig"] ?? {};
|
|
28104
|
-
const imageConfig = {};
|
|
28105
|
-
if (Array.isArray(rawImageConfig["Command"])) imageConfig.command = rawImageConfig["Command"].filter((s) => typeof s === "string");
|
|
28106
|
-
if (Array.isArray(rawImageConfig["EntryPoint"])) imageConfig.entryPoint = rawImageConfig["EntryPoint"].filter((s) => typeof s === "string");
|
|
28107
|
-
if (typeof rawImageConfig["WorkingDirectory"] === "string") imageConfig.workingDirectory = rawImageConfig["WorkingDirectory"];
|
|
28108
|
-
return {
|
|
28109
|
-
kind: "image",
|
|
28110
|
-
stack,
|
|
28111
|
-
logicalId,
|
|
28112
|
-
resource,
|
|
28113
|
-
memoryMb,
|
|
28114
|
-
timeoutSec,
|
|
28115
|
-
imageUri,
|
|
28116
|
-
imageConfig,
|
|
28117
|
-
architecture: extractArchitecture(props, logicalId),
|
|
28118
|
-
layers: [],
|
|
28119
|
-
...ephemeralStorageMb !== void 0 && { ephemeralStorageMb }
|
|
28120
|
-
};
|
|
28121
|
-
}
|
|
28122
|
-
|
|
28123
|
-
// src/local/lambda-resolver/target.ts
|
|
28124
|
-
function parseTarget(target) {
|
|
28125
|
-
if (typeof target !== "string" || target.length === 0) throw new LocalInvokeResolutionError("Empty target. Pass a CDK display path (e.g. 'MyStack/MyApi/Handler') or stack-qualified logical ID (e.g. 'MyStack:MyApiHandler1234ABCD').");
|
|
28126
|
-
const colonIdx = target.indexOf(":");
|
|
28127
|
-
const slashIdx = target.indexOf("/");
|
|
28128
|
-
if (colonIdx > 0 && (slashIdx === -1 || colonIdx < slashIdx)) {
|
|
28129
|
-
const stackPattern = target.substring(0, colonIdx);
|
|
28130
|
-
const pathOrId = target.substring(colonIdx + 1);
|
|
28131
|
-
if (pathOrId.length === 0) throw new LocalInvokeResolutionError(`Target '${target}' has no logical ID after ':'.`);
|
|
28132
|
-
return {
|
|
28133
|
-
stackPattern,
|
|
28134
|
-
pathOrId,
|
|
28135
|
-
isPath: pathOrId.includes("/")
|
|
28136
|
-
};
|
|
28137
|
-
}
|
|
28138
|
-
if (slashIdx > 0) return {
|
|
28139
|
-
stackPattern: target.substring(0, slashIdx),
|
|
28140
|
-
pathOrId: target,
|
|
28141
|
-
isPath: true
|
|
28142
|
-
};
|
|
28143
|
-
return {
|
|
28144
|
-
stackPattern: null,
|
|
28145
|
-
pathOrId: target,
|
|
28146
|
-
isPath: false
|
|
28147
|
-
};
|
|
28148
|
-
}
|
|
28149
|
-
function resolveLambdaTarget(target, stacks) {
|
|
28150
|
-
if (stacks.length === 0) throw new LocalInvokeResolutionError("No stacks found in the synthesized assembly.");
|
|
28151
|
-
const parsed = parseTarget(target);
|
|
28152
|
-
const stack = pickStack$1(parsed, stacks, target);
|
|
28153
|
-
const template = stack.template;
|
|
28154
|
-
const resources = template.Resources ?? {};
|
|
28155
|
-
let match;
|
|
28156
|
-
if (parsed.isPath) {
|
|
28157
|
-
const index = buildCdkPathIndex(template);
|
|
28158
|
-
const lambdaMatches = resolveCdkPathToLogicalIds(parsed.pathOrId, index).filter(({ logicalId }) => resources[logicalId]?.Type === "AWS::Lambda::Function");
|
|
28159
|
-
if (lambdaMatches.length === 0) throw notFoundError$1(target, stack, resources);
|
|
28160
|
-
if (lambdaMatches.length > 1) throw new LocalInvokeResolutionError(`Target '${target}' matches ${lambdaMatches.length} Lambda functions in ${stack.stackName}: ` + lambdaMatches.map((m) => m.logicalId).join(", ") + ". Refine the path or use the stack:LogicalId form.");
|
|
28161
|
-
const m = lambdaMatches[0];
|
|
28162
|
-
match = {
|
|
28163
|
-
logicalId: m.logicalId,
|
|
28164
|
-
resource: resources[m.logicalId]
|
|
28165
|
-
};
|
|
28166
|
-
} else {
|
|
28167
|
-
const resource = resources[parsed.pathOrId];
|
|
28168
|
-
if (!resource) throw notFoundError$1(target, stack, resources);
|
|
28169
|
-
match = {
|
|
28170
|
-
logicalId: parsed.pathOrId,
|
|
28171
|
-
resource
|
|
28172
|
-
};
|
|
28173
|
-
}
|
|
28174
|
-
const { logicalId, resource } = match;
|
|
28175
|
-
if (resource.Type !== "AWS::Lambda::Function") {
|
|
28176
|
-
if (resource.Type.startsWith("Custom::")) throw new LocalInvokeResolutionError(`Resource '${logicalId}' in ${stack.stackName} is a Custom Resource (${resource.Type}), not a Lambda function. Custom Resources are invoked by the deploy framework, not by users. If you want to test the underlying handler, target the ServiceToken Lambda directly.`);
|
|
28177
|
-
throw new LocalInvokeResolutionError(`Resource '${logicalId}' in ${stack.stackName} is ${resource.Type}, not a Lambda function. cdkd local invoke only works on AWS::Lambda::Function resources in v1.`);
|
|
28178
|
-
}
|
|
28179
|
-
return extractLambdaProperties(stack, logicalId, resource, resources);
|
|
28180
|
-
}
|
|
28181
|
-
function pickStack$1(parsed, stacks, target) {
|
|
28182
|
-
const selection = selectTargetStack(parsed, target, stacks);
|
|
28183
|
-
switch (selection.kind) {
|
|
28184
|
-
case "found": return selection.stack;
|
|
28185
|
-
case "no-prefix": throw new LocalInvokeResolutionError(`Multiple stacks in app, target '${parsed.pathOrId}' is missing a stack prefix. Use 'StackName:${parsed.pathOrId}' or 'StackName/...' (path form). Available stacks: ${stacks.map(describeStack).join(", ")}.`);
|
|
28186
|
-
case "not-found": throw new LocalInvokeResolutionError(`Stack '${selection.pattern}' not found. Available stacks: ${stacks.map(describeStack).join(", ")}.`);
|
|
28187
|
-
case "ambiguous": throw new LocalInvokeResolutionError(renderAmbiguousTargetStack(selection.pattern, selection.matched));
|
|
28188
|
-
}
|
|
28189
|
-
}
|
|
28190
|
-
function notFoundError$1(target, stack, resources) {
|
|
28191
|
-
const lambdas = [];
|
|
28192
|
-
for (const [logicalId, resource] of Object.entries(resources)) {
|
|
28193
|
-
if (resource.Type !== "AWS::Lambda::Function") continue;
|
|
28194
|
-
const meta = resource.Metadata;
|
|
28195
|
-
const cdkPath = typeof meta?.["aws:cdk:path"] === "string" ? meta["aws:cdk:path"] : "";
|
|
28196
|
-
lambdas.push({
|
|
28197
|
-
displayPath: cdkPath || logicalId,
|
|
28198
|
-
logicalId
|
|
28199
|
-
});
|
|
28200
|
-
}
|
|
28201
|
-
let msg = `target '${target}' did not match any Lambda function in ${stack.stackName}.\n\n`;
|
|
28202
|
-
if (lambdas.length === 0) msg += `Stack ${stack.stackName} has no Lambda functions.`;
|
|
28203
|
-
else {
|
|
28204
|
-
const width = Math.max(...lambdas.map((l) => l.displayPath.length));
|
|
28205
|
-
msg += `Available Lambda functions in ${stack.stackName}:\n`;
|
|
28206
|
-
for (const l of lambdas) msg += ` ${l.displayPath.padEnd(width)} (${l.logicalId})\n`;
|
|
28207
|
-
}
|
|
28208
|
-
return new LocalInvokeResolutionError(msg.trimEnd());
|
|
28209
|
-
}
|
|
28210
|
-
|
|
28211
26943
|
// src/cli/commands/local-start-api/lambda-resolver.ts
|
|
28212
26944
|
function resolveLambdaByLogicalId(logicalId, stacks) {
|
|
28213
26945
|
const owners = stacksDeclaring(logicalId, stacks, LAMBDA_FUNCTION_TYPE);
|
|
@@ -28320,7 +27052,7 @@ function resolveAssetCodePath(stack, logicalId, resource) {
|
|
|
28320
27052
|
}
|
|
28321
27053
|
|
|
28322
27054
|
// src/cli/commands/local-start-api/env.ts
|
|
28323
|
-
function materializeInlineCode
|
|
27055
|
+
function materializeInlineCode(handler, source, fileExtension, tmpDirsOut) {
|
|
28324
27056
|
const lastDot = handler.lastIndexOf(".");
|
|
28325
27057
|
if (lastDot <= 0) throw new Error(`Handler '${handler}' is malformed: expected '<modulePath>.<exportName>'.`);
|
|
28326
27058
|
const modulePath = handler.substring(0, lastDot);
|
|
@@ -28368,7 +27100,217 @@ function forwardAwsEnv$2(env) {
|
|
|
28368
27100
|
if (value === void 0) continue;
|
|
28369
27101
|
env[key] = regionKeys.has(key) ? canonicalizeRegion(value) : value;
|
|
28370
27102
|
}
|
|
28371
|
-
applyCallerIdentityCredentials(env);
|
|
27103
|
+
applyCallerIdentityCredentials(env);
|
|
27104
|
+
}
|
|
27105
|
+
|
|
27106
|
+
// src/local/role-permission-emulation.ts
|
|
27107
|
+
const SESSION_POLICY_MAX_CHARS = 2048;
|
|
27108
|
+
const SESSION_POLICY_MAX_ARNS = 10;
|
|
27109
|
+
const DENY_ALL_POLICY = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Deny\",\"Action\":\"*\",\"Resource\":\"*\"}]}";
|
|
27110
|
+
function buildSessionPolicy(policies) {
|
|
27111
|
+
const { inline, managedArns } = policies;
|
|
27112
|
+
if (managedArns.length > 10) return {
|
|
27113
|
+
ok: false,
|
|
27114
|
+
reason: `the role has ${managedArns.length} managed policies, more than the ${10} STS accepts as session policies`
|
|
27115
|
+
};
|
|
27116
|
+
let policy;
|
|
27117
|
+
if (inline.length === 0) policy = managedArns.length === 0 ? DENY_ALL_POLICY : "";
|
|
27118
|
+
else {
|
|
27119
|
+
const versions = /* @__PURE__ */ new Set();
|
|
27120
|
+
const statements = [];
|
|
27121
|
+
for (const doc of inline) {
|
|
27122
|
+
if (doc === null || typeof doc !== "object" || Array.isArray(doc)) return {
|
|
27123
|
+
ok: false,
|
|
27124
|
+
reason: "an inline policy of the role is not a JSON object"
|
|
27125
|
+
};
|
|
27126
|
+
const record = doc;
|
|
27127
|
+
versions.add(typeof record["Version"] === "string" ? record["Version"] : "");
|
|
27128
|
+
const raw = record["Statement"];
|
|
27129
|
+
for (const statement of Array.isArray(raw) ? raw : raw === void 0 ? [] : [raw]) if (statement !== null && typeof statement === "object" && !Array.isArray(statement)) {
|
|
27130
|
+
const { Sid: _sid, ...rest } = statement;
|
|
27131
|
+
statements.push(rest);
|
|
27132
|
+
} else statements.push(statement);
|
|
27133
|
+
}
|
|
27134
|
+
if (versions.size > 1) return {
|
|
27135
|
+
ok: false,
|
|
27136
|
+
reason: "the inline policies of the role use different policy Version values and cannot be combined into one session policy"
|
|
27137
|
+
};
|
|
27138
|
+
const [version] = [...versions];
|
|
27139
|
+
policy = statements.length === 0 ? managedArns.length === 0 ? DENY_ALL_POLICY : "" : JSON.stringify({
|
|
27140
|
+
...version !== void 0 && version !== "" && { Version: version },
|
|
27141
|
+
Statement: statements
|
|
27142
|
+
});
|
|
27143
|
+
}
|
|
27144
|
+
const chars = policy.length + managedArns.reduce((sum, arn) => sum + arn.length, 0);
|
|
27145
|
+
if (chars > 2048) return {
|
|
27146
|
+
ok: false,
|
|
27147
|
+
reason: `the role's policies take ${chars} characters as session policies, more than the ${SESSION_POLICY_MAX_CHARS} STS accepts`
|
|
27148
|
+
};
|
|
27149
|
+
return {
|
|
27150
|
+
ok: true,
|
|
27151
|
+
policy,
|
|
27152
|
+
policyArns: managedArns
|
|
27153
|
+
};
|
|
27154
|
+
}
|
|
27155
|
+
function isIamUserArn(arn) {
|
|
27156
|
+
return arn !== void 0 && /^arn:[^:]+:iam::\d{12}:user\//.test(arn);
|
|
27157
|
+
}
|
|
27158
|
+
function isAssumeRoleAccessDenied(err) {
|
|
27159
|
+
return err?.name === "AccessDenied";
|
|
27160
|
+
}
|
|
27161
|
+
function roleNameOf(roleArn) {
|
|
27162
|
+
const resource = roleArn.split(":").slice(5).join(":");
|
|
27163
|
+
return resource.slice(resource.lastIndexOf("/") + 1);
|
|
27164
|
+
}
|
|
27165
|
+
const noticedRoles = /* @__PURE__ */ new Set();
|
|
27166
|
+
const failedRoles = /* @__PURE__ */ new Set();
|
|
27167
|
+
async function emulateRoleAfterDeniedAssume(err, args) {
|
|
27168
|
+
if (!isAssumeRoleAccessDenied(err)) return void 0;
|
|
27169
|
+
try {
|
|
27170
|
+
return await emulate(args);
|
|
27171
|
+
} catch (unexpected) {
|
|
27172
|
+
if (failedRoles.has(args.roleArn)) return void 0;
|
|
27173
|
+
failedRoles.add(args.roleArn);
|
|
27174
|
+
getLogger().warn(safeMsg`${args.flag}: emulating the role's permissions failed: ${describeLocalAwsFailureForWarn(unexpected, "role permission emulation")}.`);
|
|
27175
|
+
return;
|
|
27176
|
+
}
|
|
27177
|
+
}
|
|
27178
|
+
async function emulate(args) {
|
|
27179
|
+
const logger = getLogger();
|
|
27180
|
+
const shownRole = displayIdent(args.roleArn, { maxCodePoints: 613 });
|
|
27181
|
+
const cannot = (reason) => {
|
|
27182
|
+
if (failedRoles.has(args.roleArn)) return void 0;
|
|
27183
|
+
failedRoles.add(args.roleArn);
|
|
27184
|
+
logger.warn(safeMsg`${args.flag}: AssumeRole(${shownRole}) was refused, and cdkd cannot emulate the role's permissions instead: ${reason}.`);
|
|
27185
|
+
};
|
|
27186
|
+
const { STSClient, GetCallerIdentityCommand, GetFederationTokenCommand } = await import("@aws-sdk/client-sts");
|
|
27187
|
+
const sts = new STSClient({
|
|
27188
|
+
...awsClientDefaults({
|
|
27189
|
+
ignoreAssumedRole: true,
|
|
27190
|
+
realAws: args.realAws
|
|
27191
|
+
}),
|
|
27192
|
+
...args.region && { region: args.region }
|
|
27193
|
+
});
|
|
27194
|
+
try {
|
|
27195
|
+
let callerArn;
|
|
27196
|
+
try {
|
|
27197
|
+
callerArn = (await sts.send(new GetCallerIdentityCommand({}))).Arn;
|
|
27198
|
+
} catch (idErr) {
|
|
27199
|
+
return cannot(describeLocalAwsFailureForWarn(idErr, "STS GetCallerIdentity"));
|
|
27200
|
+
}
|
|
27201
|
+
const roleAccount = parseIamRoleArn(args.roleArn)?.accountId;
|
|
27202
|
+
if (roleAccount === void 0 || roleAccount !== callerArn?.split(":")[4]) return cannot("the role is not in your credentials' account, so its policies cannot be read");
|
|
27203
|
+
if (args.emulateRoleVia === void 0 && !isIamUserArn(callerArn)) return cannot("your credentials are not an IAM user, and only an IAM user can call sts:GetFederationToken. Pass --emulate-role-via <arn> naming a role you can assume, and cdkd assumes it with the role's policies as session policies");
|
|
27204
|
+
let policies;
|
|
27205
|
+
try {
|
|
27206
|
+
policies = await readRolePolicies(args);
|
|
27207
|
+
} catch (readErr) {
|
|
27208
|
+
return cannot(`reading the role's policies failed (it needs iam:GetRole, iam:ListRolePolicies, iam:GetRolePolicy and iam:ListAttachedRolePolicies): ${describeLocalAwsFailureForWarn(readErr, "IAM role policy read")}`);
|
|
27209
|
+
}
|
|
27210
|
+
if (policies.permissionsBoundaryArn !== void 0) return cannot(`the role has a permissions boundary (${displayIdent(policies.permissionsBoundaryArn)}), which session policies cannot reproduce, so the emulation could allow what the role cannot`);
|
|
27211
|
+
const plan = buildSessionPolicy(policies);
|
|
27212
|
+
if (!plan.ok) return cannot(plan.reason);
|
|
27213
|
+
const sessionPolicies = {
|
|
27214
|
+
...plan.policy !== "" && { Policy: plan.policy },
|
|
27215
|
+
...plan.policyArns.length > 0 && { PolicyArns: plan.policyArns.map((arn) => ({ arn })) }
|
|
27216
|
+
};
|
|
27217
|
+
let via;
|
|
27218
|
+
let response;
|
|
27219
|
+
try {
|
|
27220
|
+
if (args.emulateRoleVia !== void 0) {
|
|
27221
|
+
via = `AssumeRole of --emulate-role-via ${displayIdent(args.emulateRoleVia, { maxCodePoints: 613 })}`;
|
|
27222
|
+
response = await sts.send(sendableAssumeRoleCommand({
|
|
27223
|
+
RoleArn: args.emulateRoleVia,
|
|
27224
|
+
RoleSessionName: `${args.sessionNamePrefix}-emulate-${Date.now()}`,
|
|
27225
|
+
DurationSeconds: 3600,
|
|
27226
|
+
...sessionPolicies
|
|
27227
|
+
}));
|
|
27228
|
+
} else {
|
|
27229
|
+
via = "sts:GetFederationToken";
|
|
27230
|
+
response = await sts.send(new GetFederationTokenCommand({
|
|
27231
|
+
Name: `cdkd-${Date.now()}`,
|
|
27232
|
+
DurationSeconds: 3600,
|
|
27233
|
+
...sessionPolicies
|
|
27234
|
+
}));
|
|
27235
|
+
}
|
|
27236
|
+
} catch (stsErr) {
|
|
27237
|
+
const stsName = stsErr?.name;
|
|
27238
|
+
if (stsName === "PackedPolicyTooLargeException" || stsName === "PackedPolicyTooLarge") return cannot("the role's policies are larger than STS accepts as session policies (PackedPolicyTooLarge)");
|
|
27239
|
+
const rendered = describeLocalAwsFailureForWarn(stsErr, "STS session-policy credentials");
|
|
27240
|
+
return cannot(args.emulateRoleVia === void 0 ? `${rendered}. Temporary IAM user credentials (GetSessionToken / MFA) cannot call sts:GetFederationToken; pass --emulate-role-via <arn> naming a role you can assume instead` : rendered);
|
|
27241
|
+
}
|
|
27242
|
+
const creds = response.Credentials;
|
|
27243
|
+
if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) return cannot("STS returned no usable credentials");
|
|
27244
|
+
if (!noticedRoles.has(args.roleArn)) {
|
|
27245
|
+
noticedRoles.add(args.roleArn);
|
|
27246
|
+
const count = policies.inline.length + policies.managedArns.length;
|
|
27247
|
+
const who = args.emulateRoleVia !== void 0 ? "that role" : "you";
|
|
27248
|
+
const federationNote = args.emulateRoleVia === void 0 ? " A GetFederationToken session cannot call IAM, nor STS except GetCallerIdentity." : "";
|
|
27249
|
+
logger.warn(safeMsg`${args.flag}: AssumeRole(${shownRole}) was refused (the role's trust policy does not allow you), so cdkd EMULATES its permissions: credentials from ${via} with the role's ${policies.inline.length} inline and ${policies.managedArns.length} managed ${count === 1 ? "policy" : "policies"} as session policies, which allow only what both ${who} and the role allow. This is an APPROXIMATION: resource-based policies, KMS key policies and aws:PrincipalArn conditions that name the role see a different principal, and the role's session tags are not reproduced. Policy variables such as aws:username and aws:userid take this session's values, not the role's (a role session has no aws:username).${federationNote}`);
|
|
27250
|
+
}
|
|
27251
|
+
return {
|
|
27252
|
+
accessKeyId: creds.AccessKeyId,
|
|
27253
|
+
secretAccessKey: creds.SecretAccessKey,
|
|
27254
|
+
sessionToken: creds.SessionToken
|
|
27255
|
+
};
|
|
27256
|
+
} finally {
|
|
27257
|
+
sts.destroy();
|
|
27258
|
+
}
|
|
27259
|
+
}
|
|
27260
|
+
async function readRolePolicies(args) {
|
|
27261
|
+
const { IAMClient, GetRoleCommand, ListRolePoliciesCommand, GetRolePolicyCommand, ListAttachedRolePoliciesCommand } = await import("@aws-sdk/client-iam");
|
|
27262
|
+
const iam = new IAMClient({
|
|
27263
|
+
...awsClientDefaults({
|
|
27264
|
+
ignoreAssumedRole: true,
|
|
27265
|
+
realAws: args.realAws
|
|
27266
|
+
}),
|
|
27267
|
+
...args.region && { region: args.region }
|
|
27268
|
+
});
|
|
27269
|
+
const RoleName = roleNameOf(args.roleArn);
|
|
27270
|
+
try {
|
|
27271
|
+
const permissionsBoundaryArn = (await iam.send(new GetRoleCommand({ RoleName }))).Role?.PermissionsBoundary?.PermissionsBoundaryArn;
|
|
27272
|
+
const names = [];
|
|
27273
|
+
let marker;
|
|
27274
|
+
do {
|
|
27275
|
+
const page = await iam.send(new ListRolePoliciesCommand({
|
|
27276
|
+
RoleName,
|
|
27277
|
+
...marker && { Marker: marker }
|
|
27278
|
+
}));
|
|
27279
|
+
names.push(...page.PolicyNames ?? []);
|
|
27280
|
+
marker = page.IsTruncated ? page.Marker : void 0;
|
|
27281
|
+
} while (marker);
|
|
27282
|
+
const inline = [];
|
|
27283
|
+
for (const PolicyName of names) {
|
|
27284
|
+
const got = await iam.send(new GetRolePolicyCommand({
|
|
27285
|
+
RoleName,
|
|
27286
|
+
PolicyName
|
|
27287
|
+
}));
|
|
27288
|
+
let doc;
|
|
27289
|
+
try {
|
|
27290
|
+
doc = JSON.parse(decodeURIComponent(got.PolicyDocument ?? "{}"));
|
|
27291
|
+
} catch {
|
|
27292
|
+
throw new Error("an inline policy document of the role is not valid JSON");
|
|
27293
|
+
}
|
|
27294
|
+
inline.push(doc);
|
|
27295
|
+
}
|
|
27296
|
+
const managedArns = [];
|
|
27297
|
+
let attachedMarker;
|
|
27298
|
+
do {
|
|
27299
|
+
const page = await iam.send(new ListAttachedRolePoliciesCommand({
|
|
27300
|
+
RoleName,
|
|
27301
|
+
...attachedMarker && { Marker: attachedMarker }
|
|
27302
|
+
}));
|
|
27303
|
+
for (const attached of page.AttachedPolicies ?? []) if (attached.PolicyArn) managedArns.push(attached.PolicyArn);
|
|
27304
|
+
attachedMarker = page.IsTruncated ? page.Marker : void 0;
|
|
27305
|
+
} while (attachedMarker);
|
|
27306
|
+
return {
|
|
27307
|
+
inline,
|
|
27308
|
+
managedArns,
|
|
27309
|
+
...permissionsBoundaryArn !== void 0 && { permissionsBoundaryArn }
|
|
27310
|
+
};
|
|
27311
|
+
} finally {
|
|
27312
|
+
iam.destroy();
|
|
27313
|
+
}
|
|
28372
27314
|
}
|
|
28373
27315
|
|
|
28374
27316
|
// src/cli/commands/local-start-api/credentials.ts
|
|
@@ -28405,7 +27347,7 @@ function forceExitShutdownWarning(signal, hostPath) {
|
|
|
28405
27347
|
const stranded = strandedProfileCredentialsNotice(hostPath);
|
|
28406
27348
|
return `Received second ${signal}; force-exiting. Orphan containers may remain — run 'docker ps --filter name=cdkd-local-' and 'docker rm -f' to clean up.` + (stranded === void 0 ? "" : ` ${stranded}`);
|
|
28407
27349
|
}
|
|
28408
|
-
async function assumeLambdaExecutionRole$1(roleArn, region) {
|
|
27350
|
+
async function assumeLambdaExecutionRole$1(roleArn, region, emulateRoleVia) {
|
|
28409
27351
|
assertSendableRoleArn(roleArn);
|
|
28410
27352
|
const { STSClient } = await import("@aws-sdk/client-sts");
|
|
28411
27353
|
const sts = new STSClient({
|
|
@@ -28429,6 +27371,15 @@ async function assumeLambdaExecutionRole$1(roleArn, region) {
|
|
|
28429
27371
|
};
|
|
28430
27372
|
} catch (err) {
|
|
28431
27373
|
if (err instanceof CdkdError) throw err;
|
|
27374
|
+
const emulated = await emulateRoleAfterDeniedAssume(err, {
|
|
27375
|
+
roleArn,
|
|
27376
|
+
region,
|
|
27377
|
+
realAws: mixedModeActive(),
|
|
27378
|
+
...emulateRoleVia !== void 0 && { emulateRoleVia },
|
|
27379
|
+
flag: "--assume-role",
|
|
27380
|
+
sessionNamePrefix: "cdkd-local-start-api"
|
|
27381
|
+
});
|
|
27382
|
+
if (emulated) return emulated;
|
|
28432
27383
|
const rendered = describeLocalAwsFailureForWarn(err, "STS AssumeRole");
|
|
28433
27384
|
throw new CdkdError(`--assume-role: STS AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) failed: ${rendered}.`, "LOCAL_START_API_ASSUMEROLE_FAILED", redactedAwsCause(err, "STS AssumeRole failed"));
|
|
28434
27385
|
} finally {
|
|
@@ -28581,6 +27532,67 @@ function extractImageString(value) {
|
|
|
28581
27532
|
}
|
|
28582
27533
|
}
|
|
28583
27534
|
|
|
27535
|
+
// src/local/ecs-task-resolver/role-arn.ts
|
|
27536
|
+
const TASK_ROLE_ACCOUNT_PLACEHOLDER = "${AWS::AccountId}";
|
|
27537
|
+
const TASK_ROLE_PARTITION_PLACEHOLDER = "${AWS::Partition}";
|
|
27538
|
+
function placeholderRoleArn(pathAndName) {
|
|
27539
|
+
return `arn:${TASK_ROLE_PARTITION_PLACEHOLDER}:iam::${TASK_ROLE_ACCOUNT_PLACEHOLDER}:role${pathAndName}`;
|
|
27540
|
+
}
|
|
27541
|
+
function sameStackRoleLogicalId(value, resources) {
|
|
27542
|
+
if (!value || typeof value !== "object") return void 0;
|
|
27543
|
+
const obj = value;
|
|
27544
|
+
let refLogicalId;
|
|
27545
|
+
if ("Ref" in obj && typeof obj["Ref"] === "string") refLogicalId = obj["Ref"];
|
|
27546
|
+
else if ("Fn::GetAtt" in obj) {
|
|
27547
|
+
const arg = obj["Fn::GetAtt"];
|
|
27548
|
+
if (Array.isArray(arg) && typeof arg[0] === "string") {
|
|
27549
|
+
const attr = typeof arg[1] === "string" ? arg[1] : "";
|
|
27550
|
+
if (attr === "" || attr === "Arn") refLogicalId = arg[0];
|
|
27551
|
+
}
|
|
27552
|
+
}
|
|
27553
|
+
if (refLogicalId === void 0) return void 0;
|
|
27554
|
+
return resources[refLogicalId]?.Type === "AWS::IAM::Role" ? refLogicalId : void 0;
|
|
27555
|
+
}
|
|
27556
|
+
function roleArnFromStateRecord(logicalId, role, subContext) {
|
|
27557
|
+
if (!subContext) return { reason: "no-state" };
|
|
27558
|
+
const record = subContext.resources[logicalId];
|
|
27559
|
+
if (!record) return { reason: "no-record" };
|
|
27560
|
+
const arn = record.attributes?.["Arn"];
|
|
27561
|
+
if (typeof arn === "string" && arn.length > 0) return { arn };
|
|
27562
|
+
const name = record.physicalId;
|
|
27563
|
+
if (typeof name !== "string" || name.length === 0) return { reason: "no-record" };
|
|
27564
|
+
const rawPath = role.Properties?.["Path"];
|
|
27565
|
+
if (rawPath === void 0) return { arn: placeholderRoleArn(`/${name}`) };
|
|
27566
|
+
if (typeof rawPath !== "string" || !/^\/(?:.*\/)?$/.test(rawPath)) return { reason: "path-not-literal" };
|
|
27567
|
+
return { arn: placeholderRoleArn(`${rawPath}${name}`) };
|
|
27568
|
+
}
|
|
27569
|
+
function resolveRoleArn(value, resources, subContext) {
|
|
27570
|
+
if (value === void 0 || value === null) return {};
|
|
27571
|
+
if (typeof value === "string") return { arn: value };
|
|
27572
|
+
if (typeof value !== "object") return {};
|
|
27573
|
+
const obj = value;
|
|
27574
|
+
if ("Ref" in obj || "Fn::GetAtt" in obj) {
|
|
27575
|
+
const logicalId = sameStackRoleLogicalId(value, resources);
|
|
27576
|
+
if (logicalId === void 0) return {};
|
|
27577
|
+
const fromState = roleArnFromStateRecord(logicalId, resources[logicalId], subContext);
|
|
27578
|
+
if ("arn" in fromState) return { arn: fromState.arn };
|
|
27579
|
+
return {
|
|
27580
|
+
arn: placeholderRoleArn(`/${logicalId}`),
|
|
27581
|
+
unresolved: {
|
|
27582
|
+
logicalId,
|
|
27583
|
+
reason: fromState.reason
|
|
27584
|
+
}
|
|
27585
|
+
};
|
|
27586
|
+
}
|
|
27587
|
+
if ("Fn::Join" in obj || "Fn::Sub" in obj) {
|
|
27588
|
+
if (!subContext) return {};
|
|
27589
|
+
const sub = substituteAgainstState(value, subContext);
|
|
27590
|
+
if (sub.kind === "literal" && typeof sub.value === "string" && sub.value.length > 0) return { arn: sub.value };
|
|
27591
|
+
return {};
|
|
27592
|
+
}
|
|
27593
|
+
return {};
|
|
27594
|
+
}
|
|
27595
|
+
|
|
28584
27596
|
// src/local/ecs-task-resolver/needs.ts
|
|
28585
27597
|
function detectEcsImageResolutionNeeds(stack) {
|
|
28586
27598
|
const resources = stack.template.Resources ?? {};
|
|
@@ -28589,6 +27601,7 @@ function detectEcsImageResolutionNeeds(stack) {
|
|
|
28589
27601
|
let needsEnvOrSecretSubstitution = false;
|
|
28590
27602
|
let needsCrossStackResolver = false;
|
|
28591
27603
|
let needsAssetRepoMarker = false;
|
|
27604
|
+
let needsTaskRoleState = false;
|
|
28592
27605
|
for (const res of Object.values(resources)) {
|
|
28593
27606
|
if (res.Type !== "AWS::ECS::TaskDefinition") continue;
|
|
28594
27607
|
const props = res.Properties ?? {};
|
|
@@ -28615,6 +27628,7 @@ function detectEcsImageResolutionNeeds(stack) {
|
|
|
28615
27628
|
break;
|
|
28616
27629
|
}
|
|
28617
27630
|
}
|
|
27631
|
+
if (sameStackRoleLogicalId(props["TaskRoleArn"], resources) !== void 0) needsTaskRoleState = true;
|
|
28618
27632
|
if (isFnJoinOrSubIntrinsic(props["TaskRoleArn"]) || isFnJoinOrSubIntrinsic(props["ExecutionRoleArn"])) needsEnvOrSecretSubstitution = true;
|
|
28619
27633
|
}
|
|
28620
27634
|
return {
|
|
@@ -28622,7 +27636,8 @@ function detectEcsImageResolutionNeeds(stack) {
|
|
|
28622
27636
|
needsStateResources,
|
|
28623
27637
|
needsEnvOrSecretSubstitution,
|
|
28624
27638
|
needsCrossStackResolver,
|
|
28625
|
-
needsAssetRepoMarker
|
|
27639
|
+
needsAssetRepoMarker,
|
|
27640
|
+
needsTaskRoleState
|
|
28626
27641
|
};
|
|
28627
27642
|
}
|
|
28628
27643
|
function containerHasCrossStackEnvOrSecret(c) {
|
|
@@ -28939,34 +27954,6 @@ function buildSubstitutionContextFromImageContext(context) {
|
|
|
28939
27954
|
return subContext;
|
|
28940
27955
|
}
|
|
28941
27956
|
|
|
28942
|
-
// src/local/ecs-task-resolver/role-arn.ts
|
|
28943
|
-
const TASK_ROLE_ACCOUNT_PLACEHOLDER = "${AWS::AccountId}";
|
|
28944
|
-
function resolveRoleArn(value, resources, subContext) {
|
|
28945
|
-
if (value === void 0 || value === null) return void 0;
|
|
28946
|
-
if (typeof value === "string") return value;
|
|
28947
|
-
if (typeof value !== "object") return void 0;
|
|
28948
|
-
const obj = value;
|
|
28949
|
-
let refLogicalId;
|
|
28950
|
-
if ("Ref" in obj && typeof obj["Ref"] === "string") refLogicalId = obj["Ref"];
|
|
28951
|
-
else if ("Fn::GetAtt" in obj) {
|
|
28952
|
-
const arg = obj["Fn::GetAtt"];
|
|
28953
|
-
if (Array.isArray(arg) && typeof arg[0] === "string") {
|
|
28954
|
-
const attr = typeof arg[1] === "string" ? arg[1] : "";
|
|
28955
|
-
if (attr === "" || attr === "Arn") refLogicalId = arg[0];
|
|
28956
|
-
}
|
|
28957
|
-
}
|
|
28958
|
-
if (refLogicalId !== void 0) {
|
|
28959
|
-
if (resources[refLogicalId]?.Type !== "AWS::IAM::Role") return void 0;
|
|
28960
|
-
return `arn:aws:iam::${TASK_ROLE_ACCOUNT_PLACEHOLDER}:role/${refLogicalId}`;
|
|
28961
|
-
}
|
|
28962
|
-
if ("Fn::Join" in obj || "Fn::Sub" in obj) {
|
|
28963
|
-
if (!subContext) return void 0;
|
|
28964
|
-
const sub = substituteAgainstState(value, subContext);
|
|
28965
|
-
if (sub.kind === "literal" && typeof sub.value === "string" && sub.value.length > 0) return sub.value;
|
|
28966
|
-
return;
|
|
28967
|
-
}
|
|
28968
|
-
}
|
|
28969
|
-
|
|
28970
27957
|
// src/local/ecs-task-resolver/volume.ts
|
|
28971
27958
|
function parseVolume(raw, idx, taskLogicalId, subContext) {
|
|
28972
27959
|
if (!raw || typeof raw !== "object") throw new EcsTaskResolutionError(`Task '${taskLogicalId}' Volumes[${idx}] is not an object.`);
|
|
@@ -29101,8 +28088,13 @@ function extractTaskDefinitionProperties(stack, logicalId, resource, context) {
|
|
|
29101
28088
|
if (props["ProxyConfiguration"]) warnings.push(`Task definition '${logicalId}' declares 'ProxyConfiguration' (custom Envoy / App Mesh bootstrap), which is NOT honored by 'cdkd local start-service' / 'cdkd local run-task' in v1. Local execution will run without the configured proxy. See design doc § 2 for the rationale.`);
|
|
29102
28089
|
const resources = stack.template.Resources ?? {};
|
|
29103
28090
|
const subContext = buildSubstitutionContextFromImageContext(context);
|
|
29104
|
-
const
|
|
29105
|
-
|
|
28091
|
+
const roleSubContext = context?.ignoreStateForRoles && subContext ? {
|
|
28092
|
+
...subContext,
|
|
28093
|
+
resources: Object.fromEntries(Object.entries(subContext.resources).filter(([, r]) => r.resourceType !== "AWS::IAM::Role"))
|
|
28094
|
+
} : subContext;
|
|
28095
|
+
const taskRole = resolveRoleArn(props["TaskRoleArn"], resources, roleSubContext);
|
|
28096
|
+
const taskRoleArn = taskRole.arn;
|
|
28097
|
+
const executionRoleArn = resolveRoleArn(props["ExecutionRoleArn"], resources, roleSubContext).arn;
|
|
29106
28098
|
const runtimePlatform = parseRuntimePlatform(props["RuntimePlatform"]);
|
|
29107
28099
|
const rawContainers = props["ContainerDefinitions"];
|
|
29108
28100
|
if (!Array.isArray(rawContainers) || rawContainers.length === 0) throw new EcsTaskResolutionError(`Task definition '${logicalId}' has no ContainerDefinitions.`);
|
|
@@ -29123,6 +28115,7 @@ function extractTaskDefinitionProperties(stack, logicalId, resource, context) {
|
|
|
29123
28115
|
warnings
|
|
29124
28116
|
};
|
|
29125
28117
|
if (taskRoleArn !== void 0) out.taskRoleArn = taskRoleArn;
|
|
28118
|
+
if (taskRole.unresolved !== void 0) out.taskRoleUnresolved = taskRole.unresolved;
|
|
29126
28119
|
if (executionRoleArn !== void 0) out.executionRoleArn = executionRoleArn;
|
|
29127
28120
|
if (runtimePlatform !== void 0) out.runtimePlatform = runtimePlatform;
|
|
29128
28121
|
return out;
|
|
@@ -29366,15 +28359,15 @@ async function resolvePseudoParametersForStartApi(stateRegion, options) {
|
|
|
29366
28359
|
|
|
29367
28360
|
// src/cli/commands/local-start-api/container-spec.ts
|
|
29368
28361
|
async function buildContainerSpec(args) {
|
|
29369
|
-
const { logicalId, stacks, overrides, assumeRole, containerHost, debugPort, stsRegion, inlineTmpDirs, layerTmpDirs, stateByStack, stateSourceActive, skipPull, layerRoleArn, profileCredentials, profileCredsFile, profile, stackRegionOverride } = args;
|
|
28362
|
+
const { logicalId, stacks, overrides, assumeRole, containerHost, debugPort, stsRegion, inlineTmpDirs, layerTmpDirs, stateByStack, stateSourceActive, skipPull, layerRoleArn, emulateRoleVia, profileCredentials, profileCredsFile, profile, stackRegionOverride } = args;
|
|
29370
28363
|
const lambda = resolveLambdaByLogicalId(logicalId, stacks);
|
|
29371
28364
|
let codeDir;
|
|
29372
28365
|
let optDir;
|
|
29373
28366
|
let imageRef;
|
|
29374
28367
|
let platform;
|
|
29375
28368
|
if (lambda.kind === "zip") {
|
|
29376
|
-
codeDir = lambda.codePath ?? materializeInlineCode
|
|
29377
|
-
optDir = await materializeLambdaLayers
|
|
28369
|
+
codeDir = lambda.codePath ?? materializeInlineCode(lambda.handler, lambda.inlineCode ?? "", resolveRuntimeFileExtension(lambda.runtime), inlineTmpDirs);
|
|
28370
|
+
optDir = await materializeLambdaLayers(lambda.layers, layerTmpDirs, layerRoleArn, {
|
|
29378
28371
|
logicalId,
|
|
29379
28372
|
cdkPath: readCdkPathOrUndefined(lambda.resource)
|
|
29380
28373
|
});
|
|
@@ -29441,15 +28434,20 @@ async function buildContainerSpec(args) {
|
|
|
29441
28434
|
lambdaResource: lambda.resource,
|
|
29442
28435
|
stateBundle
|
|
29443
28436
|
});
|
|
28437
|
+
const containerRegion = await resolveContainerRegion({
|
|
28438
|
+
region: stsRegion,
|
|
28439
|
+
stackRegion: lambda.stack.region,
|
|
28440
|
+
stateRegion: stateBundle?.region,
|
|
28441
|
+
profile
|
|
28442
|
+
});
|
|
29444
28443
|
if (roleArn) {
|
|
29445
|
-
const creds = await assumeLambdaExecutionRole$1(roleArn,
|
|
28444
|
+
const creds = await assumeLambdaExecutionRole$1(roleArn, containerRegion, emulateRoleVia);
|
|
29446
28445
|
dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
|
|
29447
28446
|
dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
|
|
29448
28447
|
dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
|
|
29449
|
-
setContainerRegion(dockerEnv,
|
|
28448
|
+
setContainerRegion(dockerEnv, containerRegion);
|
|
29450
28449
|
} else {
|
|
29451
28450
|
forwardAwsEnv$2(dockerEnv);
|
|
29452
|
-
const containerRegion = firstUsableRegion(stsRegion, lambda.stack.region);
|
|
29453
28451
|
setContainerRegion(dockerEnv, containerRegion);
|
|
29454
28452
|
if (profileCredentials) {
|
|
29455
28453
|
dockerEnv["AWS_ACCESS_KEY_ID"] = profileCredentials.accessKeyId;
|
|
@@ -29515,10 +28513,14 @@ async function buildContainerSpec(args) {
|
|
|
29515
28513
|
}
|
|
29516
28514
|
async function resolveContainerImageForStartApi(lambda, skipPull) {
|
|
29517
28515
|
const logger = getLogger();
|
|
29518
|
-
const localBuild = await resolveLocalBuildPlan
|
|
28516
|
+
const localBuild = await resolveLocalBuildPlan(lambda);
|
|
29519
28517
|
if (localBuild) return { imageRef: await buildContainerImage$1(localBuild.asset, localBuild.cdkOutDir, {
|
|
29520
28518
|
assetOutdir: localBuild.assetOutdir,
|
|
29521
|
-
architecture: lambda.architecture
|
|
28519
|
+
architecture: lambda.architecture,
|
|
28520
|
+
workload: {
|
|
28521
|
+
logicalId: lambda.logicalId,
|
|
28522
|
+
cdkPath: readCdkPathOrUndefined(lambda.resource)
|
|
28523
|
+
}
|
|
29522
28524
|
}) };
|
|
29523
28525
|
if (!parseEcrUri(lambda.imageUri)) throw new Error(`Container Lambda '${lambda.logicalId}' has no matching asset in cdk.out, and Code.ImageUri '${lambda.imageUri}' is not an ECR URI cdkd can authenticate against. Re-synthesize the CDK app (so cdk.out includes the build context) or deploy the image to ECR first.`);
|
|
29524
28526
|
logger.info(`No matching cdk.out asset for ${lambda.imageUri}; falling back to ECR pull (uses your own credentials — this command has no --ecr-role-arn, so a cross-account image needs cross-account ECR permissions)...`);
|
|
@@ -29530,7 +28532,7 @@ async function resolveContainerImageForStartApi(lambda, skipPull) {
|
|
|
29530
28532
|
}
|
|
29531
28533
|
}) };
|
|
29532
28534
|
}
|
|
29533
|
-
async function resolveLocalBuildPlan
|
|
28535
|
+
async function resolveLocalBuildPlan(lambda) {
|
|
29534
28536
|
if (!lambda.stack.assetManifestPath) return void 0;
|
|
29535
28537
|
const { manifestDir: cdkOutDir, assetOutdir } = assetPathDirs(lambda.stack);
|
|
29536
28538
|
const manifest = await new AssetManifestLoader().loadStackManifest(lambda.stack, cdkOutDir);
|
|
@@ -29543,14 +28545,16 @@ async function resolveLocalBuildPlan$1(lambda) {
|
|
|
29543
28545
|
assetOutdir
|
|
29544
28546
|
};
|
|
29545
28547
|
}
|
|
29546
|
-
async function materializeLambdaLayers
|
|
28548
|
+
async function materializeLambdaLayers(layers, layerTmpDirs, layerRoleArn, workload) {
|
|
29547
28549
|
if (layers.length === 0) return void 0;
|
|
29548
28550
|
const flat = [];
|
|
29549
28551
|
for (const layer of layers) {
|
|
29550
28552
|
if (layer.kind === "asset") {
|
|
28553
|
+
const asset = await layerAssetDirectory(layer.assetPath);
|
|
28554
|
+
if (asset.tmpDir !== void 0) layerTmpDirs.add(asset.tmpDir);
|
|
29551
28555
|
flat.push({
|
|
29552
28556
|
logicalId: layer.logicalId,
|
|
29553
|
-
assetPath:
|
|
28557
|
+
assetPath: asset.dir
|
|
29554
28558
|
});
|
|
29555
28559
|
continue;
|
|
29556
28560
|
}
|
|
@@ -29641,6 +28645,10 @@ async function localStartApiCommand(target, options) {
|
|
|
29641
28645
|
}
|
|
29642
28646
|
warnIfDeprecatedRegion(options);
|
|
29643
28647
|
if (options.layerRoleArn !== void 0) explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn);
|
|
28648
|
+
checkEmulateRoleVia(options.emulateRoleVia, {
|
|
28649
|
+
roleFlag: "--assume-role or --assume-role-auto",
|
|
28650
|
+
roleRequested: options.assumeRole !== void 0 || options.assumeRoleAuto === true
|
|
28651
|
+
});
|
|
29644
28652
|
await activateLocalAwsAndRoleArn(options);
|
|
29645
28653
|
const normalizedAssumeRole = normalizeStartApiAssumeRole(options.assumeRole, options.assumeRoleAuto ?? false);
|
|
29646
28654
|
if (normalizedAssumeRole === void 0) delete options.assumeRole;
|
|
@@ -29732,6 +28740,7 @@ async function localStartApiCommand(target, options) {
|
|
|
29732
28740
|
stateSourceActive,
|
|
29733
28741
|
skipPull: options.pull === false,
|
|
29734
28742
|
...options.layerRoleArn !== void 0 && { layerRoleArn: options.layerRoleArn },
|
|
28743
|
+
...options.emulateRoleVia !== void 0 && { emulateRoleVia: options.emulateRoleVia },
|
|
29735
28744
|
...profileCredentials && { profileCredentials },
|
|
29736
28745
|
...profileCredsFile && { profileCredsFile },
|
|
29737
28746
|
...dynamicReferenceSpecOptions(options)
|
|
@@ -29915,7 +28924,7 @@ async function localStartApiCommand(target, options) {
|
|
|
29915
28924
|
|
|
29916
28925
|
// src/cli/commands/local-start-api.ts
|
|
29917
28926
|
function createLocalStartApiCommand() {
|
|
29918
|
-
const startApi = new Command("start-api").description("Run a long-running local HTTP server that maps API Gateway routes (REST v1, HTTP API, Function URL) to Lambda invocations against the AWS Lambda Runtime Interface Emulator (Docker required). Supports Lambda TOKEN/REQUEST authorizers, Cognito User Pool / HTTP v2 JWT authorizers, and AWS_IAM auth (REST v1 `AuthorizationType: AWS_IAM` and Function URL `AuthType: AWS_IAM` — SigV4 signature verification only; IAM policy evaluation is NOT emulated; see https://cdkd.dev/local-start-api/#aws-iam-authorization). When JWKS is unreachable, JWT authorizers fall back to pass-through (every token accepted) with a warn line — local dev fallback. VPC-config Lambdas run locally and surface a warn line at startup; their containers do NOT get attached to the deployed VPC subnets, so calls to private RDS / ElastiCache will fail.").argument("[target]", "Optional API filter. Accepts the bare CDK logical id ('MyHttpApi'; single-stack apps only), stack-qualified logical id ('MyStack:MyHttpApi'), full CDK Construct path ('MyStack/MyHttpApi/Resource'), or an ancestor Construct path that prefix-matches ('MyStack/MyHttpApi'). When omitted, every discovered API gets its own server. Mirrors `cdkd local invoke` / `cdkd local run-task` target syntax.").addOption(new Option("--port <port>", "HTTP server port (default: auto-allocate)").default("0")).addOption(new Option("--host <host>", "Bind address").default("127.0.0.1")).addOption(new Option("--stack <name>", "Stack to start (single-stack apps auto-detect)")).addOption(new Option("--warm", "Pre-start one container per Lambda at server boot").default(false)).addOption(new Option("--per-lambda-concurrency <n>", "Pool size cap per Lambda (default 2, max 4)").default("2")).addOption(new Option("--no-pull", "Skip docker pull (cached image)")).addOption(new Option("--container-host <host>", "IP the host uses to bind/probe the RIE port (must be a numeric IP — `docker run -p <ip>:<port>:8080` rejects hostnames). Defaults to 127.0.0.1.").default("127.0.0.1")).addOption(new Option("--debug-port-base <port>", "Reserve a contiguous --debug-port range (one per Lambda)")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}, \"Parameters\": {...}})")).addOption(new Option("--assume-role <arn-or-pair>", "Assume the Lambda's execution role and forward STS-issued temp creds. Two forms: (1) `--assume-role <arn>` sets a single global default ARN used for every routed Lambda; (2) `--assume-role <LogicalId>=<arn>` (repeatable) is a per-Lambda override (wins over the global default and over --assume-role-auto for the named Lambda). Pair with --assume-role-auto to auto-resolve every other Lambda. Precedence: per-Lambda > (--assume-role-auto OR global default) > unset (developer creds passed through).").argParser((raw, prev) => parseAssumeRoleToken(raw, prev))).addOption(new Option("--assume-role-auto", "Auto-resolve EACH routed Lambda's own execution role per-Lambda (literal ARN / Fn::GetAtt against template / --from-cfn-stack state). Slower boot — one STS call per Lambda — but the right shape when each Lambda's deployed role differs. Mutually exclusive with `--assume-role <arn>` (global default); errors at boot. Compatible with `--assume-role <LogicalId>=<arn>` per-Lambda overrides — the map wins for named Lambdas, auto-resolve handles the rest.").default(false)).addOption(new Option("--watch", "Hot-reload: watch the CDK app source tree and re-synth + re-discover routes on a source edit (cdk.out / node_modules / .git excluded; honors cdk.json watch.include / watch.exclude). Off by default; the server keeps the previous version serving when synth fails mid-reload.").default(false)).addOption(new Option("--stage <name>", "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives BOTH event.stageVariables and requestContext.stage, for REST v1 and HTTP API v2 alike: when a route's API has a matching templated Stage, the selected StageName is threaded into requestContext.stage. An HTTP API v2 route reports '$default' only when its API carries no AWS::ApiGatewayV2::Stage in the template — that is v2's auto-deployed stage, not a limit on what this flag can select (AWS's CreateStage accepts named stages on v2 too). An API with no Stage matching the selected name is warned about at start-up and its routes get stageVariables: null.")).addOption(new Option("--api <id>", "DEPRECATED — use the positional <target> argument instead. Same accepted forms (bare logical id, stack-qualified, Construct path, ancestor prefix). Will be removed in a future major release.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--from-state", "Read cdkd S3 state for every routed stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::Join (and AWS pseudo parameters) in Lambda env vars with the deployed physical IDs / attributes. Off by default — pre-PR warn-and-drop semantics are preserved. Turn on for stacks already deployed via cdkd deploy. Mirrors `cdkd local invoke --from-state` / `cdkd local run-task --from-state`. Re-runs against fresh state on every hot-reload firing (--watch).").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in Lambda env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name per routed stack; pass an explicit value when a single CFn stack should serve every routed stack. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).addOption(new Option("--mtls-truststore <path>", "PEM-encoded CA bundle for client-certificate verification (mutual TLS). When set, the local server switches from HTTP to HTTPS and the TLS handshake rejects clients whose certificate doesn't chain to one of these CAs. Verified certs are surfaced on the Lambda event under requestContext.identity.clientCert (REST v1) / requestContext.authentication.clientCert (HTTP API v2). Must be set together with --mtls-cert + --mtls-key; partial flag sets are rejected. Generate a CA + server + client cert for local dev: openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem -subj \"/CN=cdkd-local-ca\" -days 365; openssl req -newkey rsa:2048 -nodes -keyout server-key.pem -out server-csr.pem -subj \"/CN=localhost\"; openssl x509 -req -in server-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365; openssl req -newkey rsa:2048 -nodes -keyout client-key.pem -out client-csr.pem -subj \"/CN=client\"; openssl x509 -req -in client-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365; curl --cacert ca.pem --cert client-cert.pem --key client-key.pem https://localhost:<port>/...")).addOption(new Option("--mtls-cert <path>", "PEM-encoded server certificate for mutual TLS. Self-signed is fine for local dev. Must be set together with --mtls-truststore + --mtls-key.")).addOption(new Option("--mtls-key <path>", "PEM-encoded server private key matching --mtls-cert. Must be set together with --mtls-truststore + --mtls-cert.")).addOption(new Option("--strict-sigv4", "Opt-in: enforce strict AWS_IAM SigV4 verification. When set, requests whose signature cannot be cryptographically verified (foreign access-key-id, OR no local AWS credentials configured) are denied. DEFAULT off — warn-and-pass with a placeholder principalId, matching cdk-local's `cdkl start-api`. Enable this when you want local parity with the deployed API Gateway's signature enforcement.").default(false)).action(withErrorHandling(localStartApiCommand));
|
|
28927
|
+
const startApi = new Command("start-api").description("Run a long-running local HTTP server that maps API Gateway routes (REST v1, HTTP API, Function URL) to Lambda invocations against the AWS Lambda Runtime Interface Emulator (Docker required). Supports Lambda TOKEN/REQUEST authorizers, Cognito User Pool / HTTP v2 JWT authorizers, and AWS_IAM auth (REST v1 `AuthorizationType: AWS_IAM` and Function URL `AuthType: AWS_IAM` — SigV4 signature verification only; IAM policy evaluation is NOT emulated; see https://cdkd.dev/local-start-api/#aws-iam-authorization). When JWKS is unreachable, JWT authorizers fall back to pass-through (every token accepted) with a warn line — local dev fallback. VPC-config Lambdas run locally and surface a warn line at startup; their containers do NOT get attached to the deployed VPC subnets, so calls to private RDS / ElastiCache will fail.").argument("[target]", "Optional API filter. Accepts the bare CDK logical id ('MyHttpApi'; single-stack apps only), stack-qualified logical id ('MyStack:MyHttpApi'), full CDK Construct path ('MyStack/MyHttpApi/Resource'), or an ancestor Construct path that prefix-matches ('MyStack/MyHttpApi'). When omitted, every discovered API gets its own server. Mirrors `cdkd local invoke` / `cdkd local run-task` target syntax.").addOption(new Option("--port <port>", "HTTP server port (default: auto-allocate)").default("0")).addOption(new Option("--host <host>", "Bind address").default("127.0.0.1")).addOption(new Option("--stack <name>", "Stack to start (single-stack apps auto-detect)")).addOption(new Option("--warm", "Pre-start one container per Lambda at server boot").default(false)).addOption(new Option("--per-lambda-concurrency <n>", "Pool size cap per Lambda (default 2, max 4)").default("2")).addOption(new Option("--no-pull", "Skip docker pull (cached image)")).addOption(new Option("--container-host <host>", "IP the host uses to bind/probe the RIE port (must be a numeric IP — `docker run -p <ip>:<port>:8080` rejects hostnames). Defaults to 127.0.0.1.").default("127.0.0.1")).addOption(new Option("--debug-port-base <port>", "Reserve a contiguous --debug-port range (one per Lambda)")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}, \"Parameters\": {...}})")).addOption(new Option("--assume-role <arn-or-pair>", "Assume the Lambda's execution role and forward STS-issued temp creds. Two forms: (1) `--assume-role <arn>` sets a single global default ARN used for every routed Lambda; (2) `--assume-role <LogicalId>=<arn>` (repeatable) is a per-Lambda override (wins over the global default and over --assume-role-auto for the named Lambda). Pair with --assume-role-auto to auto-resolve every other Lambda. Precedence: per-Lambda > (--assume-role-auto OR global default) > unset (developer creds passed through).").argParser((raw, prev) => parseAssumeRoleToken(raw, prev))).addOption(new Option("--assume-role-auto", "Auto-resolve EACH routed Lambda's own execution role per-Lambda (literal ARN / Fn::GetAtt against template / --from-cfn-stack state). Slower boot — one STS call per Lambda — but the right shape when each Lambda's deployed role differs. Mutually exclusive with `--assume-role <arn>` (global default); errors at boot. Compatible with `--assume-role <LogicalId>=<arn>` per-Lambda overrides — the map wins for named Lambdas, auto-resolve handles the rest.").default(false)).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--watch", "Hot-reload: watch the CDK app source tree and re-synth + re-discover routes on a source edit (cdk.out / node_modules / .git excluded; honors cdk.json watch.include / watch.exclude). Off by default; the server keeps the previous version serving when synth fails mid-reload.").default(false)).addOption(new Option("--stage <name>", "Select an API Gateway Stage by its 'StageName'. Default: the first Stage attached to each API. Drives BOTH event.stageVariables and requestContext.stage, for REST v1 and HTTP API v2 alike: when a route's API has a matching templated Stage, the selected StageName is threaded into requestContext.stage. An HTTP API v2 route reports '$default' only when its API carries no AWS::ApiGatewayV2::Stage in the template — that is v2's auto-deployed stage, not a limit on what this flag can select (AWS's CreateStage accepts named stages on v2 too). An API with no Stage matching the selected name is warned about at start-up and its routes get stageVariables: null.")).addOption(new Option("--api <id>", "DEPRECATED — use the positional <target> argument instead. Same accepted forms (bare logical id, stack-qualified, Construct path, ancestor prefix). Will be removed in a future major release.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--from-state", "Read cdkd S3 state for every routed stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::Join (and AWS pseudo parameters) in Lambda env vars with the deployed physical IDs / attributes. Off by default — pre-PR warn-and-drop semantics are preserved. Turn on for stacks already deployed via cdkd deploy. Mirrors `cdkd local invoke --from-state` / `cdkd local run-task --from-state`. Re-runs against fresh state on every hot-reload firing (--watch).").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in Lambda env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name per routed stack; pass an explicit value when a single CFn stack should serve every routed stack. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).addOption(new Option("--mtls-truststore <path>", "PEM-encoded CA bundle for client-certificate verification (mutual TLS). When set, the local server switches from HTTP to HTTPS and the TLS handshake rejects clients whose certificate doesn't chain to one of these CAs. Verified certs are surfaced on the Lambda event under requestContext.identity.clientCert (REST v1) / requestContext.authentication.clientCert (HTTP API v2). Must be set together with --mtls-cert + --mtls-key; partial flag sets are rejected. Generate a CA + server + client cert for local dev: openssl req -x509 -newkey rsa:2048 -nodes -keyout ca-key.pem -out ca.pem -subj \"/CN=cdkd-local-ca\" -days 365; openssl req -newkey rsa:2048 -nodes -keyout server-key.pem -out server-csr.pem -subj \"/CN=localhost\"; openssl x509 -req -in server-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -days 365; openssl req -newkey rsa:2048 -nodes -keyout client-key.pem -out client-csr.pem -subj \"/CN=client\"; openssl x509 -req -in client-csr.pem -CA ca.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -days 365; curl --cacert ca.pem --cert client-cert.pem --key client-key.pem https://localhost:<port>/...")).addOption(new Option("--mtls-cert <path>", "PEM-encoded server certificate for mutual TLS. Self-signed is fine for local dev. Must be set together with --mtls-truststore + --mtls-key.")).addOption(new Option("--mtls-key <path>", "PEM-encoded server private key matching --mtls-cert. Must be set together with --mtls-truststore + --mtls-cert.")).addOption(new Option("--strict-sigv4", "Opt-in: enforce strict AWS_IAM SigV4 verification. When set, requests whose signature cannot be cryptographically verified (foreign access-key-id, OR no local AWS credentials configured) are denied. DEFAULT off — warn-and-pass with a placeholder principalId, matching cdk-local's `cdkl start-api`. Enable this when you want local parity with the deployed API Gateway's signature enforcement.").default(false)).action(withErrorHandling(localStartApiCommand));
|
|
29919
28928
|
[
|
|
29920
28929
|
...commonOptions,
|
|
29921
28930
|
...appOptions,
|
|
@@ -30513,6 +29522,15 @@ function groupSecretsByContainer(resolved) {
|
|
|
30513
29522
|
}
|
|
30514
29523
|
return out;
|
|
30515
29524
|
}
|
|
29525
|
+
function previewContainerEnv(container, envOverrides) {
|
|
29526
|
+
const previewEnv = {};
|
|
29527
|
+
for (const [k, v] of Object.entries(container.environment)) defineOwnKey(previewEnv, k, v);
|
|
29528
|
+
if (envOverrides) {
|
|
29529
|
+
applyOverrideMap(previewEnv, envOverrides["Parameters"]);
|
|
29530
|
+
applyOverrideMap(previewEnv, envOverrides[container.name]);
|
|
29531
|
+
}
|
|
29532
|
+
return previewEnv;
|
|
29533
|
+
}
|
|
30516
29534
|
function buildDockerRunArgs(opts) {
|
|
30517
29535
|
const { task, container, image, network, volumeByName, secrets, containerHost, roleArn } = opts;
|
|
30518
29536
|
const args = ["run", "-d"];
|
|
@@ -30551,12 +29569,7 @@ function buildDockerRunArgs(opts) {
|
|
|
30551
29569
|
ownerPublish.push(publish);
|
|
30552
29570
|
}
|
|
30553
29571
|
const wiring = getActiveWorkloadAwsWiring();
|
|
30554
|
-
const previewEnv =
|
|
30555
|
-
for (const [k, v] of Object.entries(container.environment)) defineOwnKey(previewEnv, k, v);
|
|
30556
|
-
if (opts.envOverrides) {
|
|
30557
|
-
applyOverrideMap(previewEnv, opts.envOverrides["Parameters"]);
|
|
30558
|
-
applyOverrideMap(previewEnv, opts.envOverrides[container.name]);
|
|
30559
|
-
}
|
|
29572
|
+
const previewEnv = previewContainerEnv(container, opts.envOverrides);
|
|
30560
29573
|
const emulatorKeysOnly = workloadGetsEmulatorKeysOnly(previewEnv, wiring);
|
|
30561
29574
|
const profileCredentialsFile = emulatorKeysOnly ? void 0 : opts.profileCredentialsFile;
|
|
30562
29575
|
if (profileCredentialsFile) both("-v", `${profileCredentialsFile.hostPath}:${profileCredentialsFile.containerPath}:ro`);
|
|
@@ -30583,11 +29596,12 @@ function buildDockerRunArgs(opts) {
|
|
|
30583
29596
|
...opts.sidecarIp !== void 0 && { sidecarIp: opts.sidecarIp }
|
|
30584
29597
|
});
|
|
30585
29598
|
Object.assign(finalEnv, metaEnv);
|
|
30586
|
-
|
|
29599
|
+
const mixedReal = taskRoleAssumedInRealAws(previewEnv, wiring) && opts.mixedModeRealTaskCredentials || opts.mixedModeRealCredentials;
|
|
29600
|
+
if (mixedReal && wiring?.mixed && !emulatorKeysOnly) {
|
|
30587
29601
|
delete finalEnv["AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"];
|
|
30588
|
-
finalEnv["AWS_ACCESS_KEY_ID"] =
|
|
30589
|
-
finalEnv["AWS_SECRET_ACCESS_KEY"] =
|
|
30590
|
-
if (
|
|
29602
|
+
finalEnv["AWS_ACCESS_KEY_ID"] = mixedReal.accessKeyId;
|
|
29603
|
+
finalEnv["AWS_SECRET_ACCESS_KEY"] = mixedReal.secretAccessKey;
|
|
29604
|
+
if (mixedReal.sessionToken) finalEnv["AWS_SESSION_TOKEN"] = mixedReal.sessionToken;
|
|
30591
29605
|
}
|
|
30592
29606
|
if (profileCredentialsFile) {
|
|
30593
29607
|
finalEnv["AWS_SHARED_CREDENTIALS_FILE"] = profileCredentialsFile.containerPath;
|
|
@@ -30601,10 +29615,16 @@ function buildDockerRunArgs(opts) {
|
|
|
30601
29615
|
applyOverrideMap(finalEnv, overrides["Parameters"]);
|
|
30602
29616
|
applyOverrideMap(finalEnv, overrides[container.name]);
|
|
30603
29617
|
}
|
|
30604
|
-
if (wiring)
|
|
30605
|
-
|
|
30606
|
-
|
|
30607
|
-
|
|
29618
|
+
if (wiring) {
|
|
29619
|
+
const task = opts.emulatorTaskCredentials;
|
|
29620
|
+
finalEnv = applyWorkloadAwsWiringToEnv(finalEnv, wiring.mode === "emulator" ? task ? {
|
|
29621
|
+
...wiring,
|
|
29622
|
+
emulatorCredentials: task
|
|
29623
|
+
} : wiring : {
|
|
29624
|
+
...wiring,
|
|
29625
|
+
env: {}
|
|
29626
|
+
});
|
|
29627
|
+
}
|
|
30608
29628
|
const sensitiveKeys = /* @__PURE__ */ new Set([
|
|
30609
29629
|
...SENSITIVE_ENV_KEYS,
|
|
30610
29630
|
...secrets.map((s) => s.name),
|
|
@@ -30635,7 +29655,7 @@ function buildDockerRunArgs(opts) {
|
|
|
30635
29655
|
both("--entrypoint", container.entryPoint[0]);
|
|
30636
29656
|
entryPointTail = container.entryPoint.slice(1);
|
|
30637
29657
|
}
|
|
30638
|
-
both(image, ...entryPointTail, ...container.command ?? []);
|
|
29658
|
+
both(...noImplicitEcrPullArgs(image), image, ...entryPointTail, ...container.command ?? []);
|
|
30639
29659
|
const loopbackPorts = wiring ? effectiveLoopbackPorts(finalEnv, wiring) : [];
|
|
30640
29660
|
return {
|
|
30641
29661
|
args,
|
|
@@ -30712,6 +29732,7 @@ async function prepareOneImage(task, container, options) {
|
|
|
30712
29732
|
const tag = `cdkd-local-run-task-${(image.assetHash ?? "single").slice(0, 16)}`;
|
|
30713
29733
|
const actualTag = await buildDockerImage(asset, cdkOutDir, {
|
|
30714
29734
|
tag,
|
|
29735
|
+
workload: { containerName: container.name },
|
|
30715
29736
|
...task.stack.assetOutdir !== void 0 && { assetOutdir: task.stack.assetOutdir },
|
|
30716
29737
|
...options.platformOverride !== void 0 && { platform: options.platformOverride },
|
|
30717
29738
|
wrapError: (stderr) => new LocalInvokeBuildError$1(`docker build failed for ECS container ${displayIdent(container.name)} (${asset.source.directory !== void 0 ? displayAssemblyPath(asset.source.directory) : asset.source.executable ? redactDockerArgvValues(asset.source.executable).join(" ") : void 0}): ${displaySafe(stderr)}`)
|
|
@@ -30968,6 +29989,12 @@ async function runEcsTask(task, options, state) {
|
|
|
30968
29989
|
const volumeByName = await realizeDockerVolumes(task.volumes, state);
|
|
30969
29990
|
if (state.closing) throw interruptedError();
|
|
30970
29991
|
const mergedAddHostFlags = mergeHostGatewayAddHostFlags(options.addHostFlags, options.hostGatewayExtraHosts);
|
|
29992
|
+
const containerRegion = await resolveContainerRegion({
|
|
29993
|
+
region: options.region,
|
|
29994
|
+
stackRegion: options.stackRegion ?? task.stack.region,
|
|
29995
|
+
stateRegion: options.stateRecordRegion,
|
|
29996
|
+
profile: options.profile
|
|
29997
|
+
});
|
|
30971
29998
|
const dockerCmds = /* @__PURE__ */ new Map();
|
|
30972
29999
|
const dockerLoopbackPorts = /* @__PURE__ */ new Map();
|
|
30973
30000
|
const dockerForwarders = /* @__PURE__ */ new Map();
|
|
@@ -30992,13 +30019,15 @@ async function runEcsTask(task, options, state) {
|
|
|
30992
30019
|
containerHost: options.containerHost,
|
|
30993
30020
|
roleArn: options.taskRoleArn,
|
|
30994
30021
|
platformOverride: options.platformOverride,
|
|
30995
|
-
region:
|
|
30022
|
+
region: containerRegion,
|
|
30996
30023
|
sidecarIp: state.network.sidecarIp,
|
|
30997
30024
|
...options.skipHostPortPublish ? { skipHostPortPublish: true } : {},
|
|
30998
30025
|
...mergedAddHostFlags.length > 0 ? { addHostFlags: mergedAddHostFlags } : {},
|
|
30999
30026
|
...(options.networkAliasesByContainer?.get(container.name)?.length ?? 0) > 0 ? { networkAliases: options.networkAliasesByContainer.get(container.name) } : {},
|
|
31000
30027
|
...options.profileCredentialsFile && { profileCredentialsFile: options.profileCredentialsFile },
|
|
31001
|
-
...options.mixedModeRealCredentials && { mixedModeRealCredentials: options.mixedModeRealCredentials }
|
|
30028
|
+
...options.mixedModeRealCredentials && { mixedModeRealCredentials: options.mixedModeRealCredentials },
|
|
30029
|
+
...options.mixedModeRealTaskCredentials && { mixedModeRealTaskCredentials: options.mixedModeRealTaskCredentials },
|
|
30030
|
+
...options.emulatorTaskCredentials && { emulatorTaskCredentials: options.emulatorTaskCredentials }
|
|
31002
30031
|
});
|
|
31003
30032
|
dockerCmds.set(container.name, built.args);
|
|
31004
30033
|
dockerLoopbackPorts.set(container.name, built.loopbackPorts);
|
|
@@ -31088,16 +30117,16 @@ async function runEcsTask(task, options, state) {
|
|
|
31088
30117
|
function readFromCfnStack(source) {
|
|
31089
30118
|
return source.fromState !== true && source.fromCfnStack !== void 0 && source.fromCfnStack !== false;
|
|
31090
30119
|
}
|
|
31091
|
-
async function resolvePlaceholderAccount(arn, source) {
|
|
30120
|
+
async function resolvePlaceholderAccount(arn, source, route) {
|
|
31092
30121
|
const { region, profile } = source;
|
|
31093
|
-
if (!arn.includes("${AWS::AccountId}")) return arn;
|
|
30122
|
+
if (!arn.includes("${AWS::AccountId}") && !arn.includes("${AWS::Partition}")) return arn;
|
|
31094
30123
|
const { STSClient, GetCallerIdentityCommand } = await import("@aws-sdk/client-sts");
|
|
31095
30124
|
let sts;
|
|
31096
30125
|
if (readFromCfnStack(source)) sts = new STSClient({
|
|
31097
30126
|
...awsClientDefaults({
|
|
31098
30127
|
profile,
|
|
31099
30128
|
ignoreAssumedRole: true,
|
|
31100
|
-
realAws:
|
|
30129
|
+
realAws: route.realAws
|
|
31101
30130
|
}),
|
|
31102
30131
|
...region && { region },
|
|
31103
30132
|
...profile && { profile }
|
|
@@ -31105,15 +30134,17 @@ async function resolvePlaceholderAccount(arn, source) {
|
|
|
31105
30134
|
else sts = new STSClient({
|
|
31106
30135
|
...awsClientDefaults({
|
|
31107
30136
|
profile,
|
|
31108
|
-
realAws:
|
|
30137
|
+
realAws: route.realAws
|
|
31109
30138
|
}),
|
|
31110
30139
|
...region && { region },
|
|
31111
30140
|
...profile && { profile }
|
|
31112
30141
|
});
|
|
31113
30142
|
try {
|
|
31114
|
-
const
|
|
30143
|
+
const identity = await sts.send(new GetCallerIdentityCommand({}));
|
|
30144
|
+
const account = identity.Account;
|
|
31115
30145
|
if (!account) throw new CdkdError(`--assume-task-role: GetCallerIdentity returned no Account; cannot resolve placeholder ARN ${plainIdentOr(arn, VALUE_NOT_SHOWN, { maxCodePoints: 613 })}. Pass the ARN explicitly: --assume-task-role '<arn>'`, "LOCAL_RUN_TASK_PLACEHOLDER_NO_ACCOUNT");
|
|
31116
|
-
|
|
30146
|
+
const partition = partitionOfArn(identity.Arn);
|
|
30147
|
+
return arn.split(TASK_ROLE_ACCOUNT_PLACEHOLDER).join(account).split(TASK_ROLE_PARTITION_PLACEHOLDER).join(partition);
|
|
31117
30148
|
} catch (err) {
|
|
31118
30149
|
if (err instanceof CdkdError) throw err;
|
|
31119
30150
|
const rendered = describeLocalAwsFailureForWarn(err, "STS GetCallerIdentity");
|
|
@@ -31122,13 +30153,27 @@ async function resolvePlaceholderAccount(arn, source) {
|
|
|
31122
30153
|
sts.destroy();
|
|
31123
30154
|
}
|
|
31124
30155
|
}
|
|
31125
|
-
|
|
30156
|
+
function taskRoleNameIsLogicalIdWarning(logicalId, reason) {
|
|
30157
|
+
const id = displayIdent(logicalId);
|
|
30158
|
+
switch (reason) {
|
|
30159
|
+
case "no-state-source": return `--assume-task-role: TaskRoleArn references the same-stack role ${id}, and without --from-state (cdkd-deployed) or --from-cfn-stack (cdk-deployed) cdkd cannot read the name it was deployed under, so cdkd assumes a role named ${id}. A role CDK names for you is deployed as '<Stack>-<LogicalId>-<suffix>', where AssumeRole fails: pass --from-state / --from-cfn-stack, or pass the ARN explicitly: --assume-task-role '<arn>'.`;
|
|
30160
|
+
case "state-not-read": return `--assume-task-role: cdkd read no state record for the task role ${id} (the target names no single stack, or the stack has no record: it is not deployed), so cdkd assumes a role named ${id}. Name the stack in the target ('<Stack>:<LogicalId>' or a display path), deploy the stack first, or pass the ARN explicitly: --assume-task-role '<arn>'.`;
|
|
30161
|
+
case "mixed-mode-emulator-iam": return `--assume-task-role: in AWS Emulator mixed mode the task role is assumed in real AWS, but the state record's IAM roles are the emulator's, so cdkd does not read ${id} from it and assumes a role named ${id}. Mark IAM as a "real-aws" exception under Parameters (AWS_ENDPOINT_URL_IAM), or pass the ARN explicitly: --assume-task-role '<arn>'.`;
|
|
30162
|
+
case "no-record": return `--assume-task-role: the state source has no record of the task role ${id}, so cdkd assumes a role named ${id}. Deploy the stack first, or pass the ARN explicitly: --assume-task-role '<arn>'.`;
|
|
30163
|
+
case "path-not-literal": return `--assume-task-role: the template's Path for the task role ${id} is not a literal IAM path, so cdkd cannot build its ARN from the stack's record, so cdkd assumes a role named ${id}. Pass the ARN explicitly: --assume-task-role '<arn>'.`;
|
|
30164
|
+
}
|
|
30165
|
+
}
|
|
30166
|
+
function partitionOfArn(arn) {
|
|
30167
|
+
const segment = arn?.split(":")[1];
|
|
30168
|
+
return arn?.startsWith("arn:") && segment ? segment : "aws";
|
|
30169
|
+
}
|
|
30170
|
+
async function assumeTaskRole(roleArn, region, route, emulateRoleVia) {
|
|
31126
30171
|
assertSendableRoleArn(roleArn);
|
|
31127
30172
|
const { STSClient } = await import("@aws-sdk/client-sts");
|
|
31128
30173
|
const sts = new STSClient({
|
|
31129
30174
|
...awsClientDefaults({
|
|
31130
30175
|
ignoreAssumedRole: true,
|
|
31131
|
-
realAws:
|
|
30176
|
+
realAws: route.realAws
|
|
31132
30177
|
}),
|
|
31133
30178
|
...region && { region }
|
|
31134
30179
|
});
|
|
@@ -31146,6 +30191,15 @@ async function assumeTaskRole(roleArn, region) {
|
|
|
31146
30191
|
};
|
|
31147
30192
|
} catch (err) {
|
|
31148
30193
|
if (err instanceof CdkdError) throw err;
|
|
30194
|
+
const emulated = await emulateRoleAfterDeniedAssume(err, {
|
|
30195
|
+
roleArn,
|
|
30196
|
+
region,
|
|
30197
|
+
realAws: route.realAws,
|
|
30198
|
+
...emulateRoleVia !== void 0 && { emulateRoleVia },
|
|
30199
|
+
flag: "--assume-task-role",
|
|
30200
|
+
sessionNamePrefix: "cdkd-local-run-task"
|
|
30201
|
+
});
|
|
30202
|
+
if (emulated) return emulated;
|
|
31149
30203
|
const rendered = describeLocalAwsFailureForWarn(err, "STS AssumeRole");
|
|
31150
30204
|
throw new CdkdError(`--assume-task-role: STS AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) failed: ${rendered}.`, "LOCAL_RUN_TASK_ASSUMEROLE_FAILED", redactedAwsCause(err, "STS AssumeRole failed"));
|
|
31151
30205
|
} finally {
|
|
@@ -31189,8 +30243,11 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
|
|
|
31189
30243
|
const logger = getLogger();
|
|
31190
30244
|
if (!candidate) return {};
|
|
31191
30245
|
const needs = detectEcsImageResolutionNeeds(candidate);
|
|
31192
|
-
|
|
30246
|
+
const roleRecordUsable = !taskRoleRecordIsEmulatorSide();
|
|
30247
|
+
const wantsStateForTaskRole = !!stateProvider && needs.needsTaskRoleState && options.assumeTaskRole === true && roleRecordUsable;
|
|
30248
|
+
if (!needs.needsPseudoParameters && !needs.needsStateResources && !needs.needsEnvOrSecretSubstitution && !needs.needsAssetRepoMarker && !wantsStateForTaskRole) return {};
|
|
31193
30249
|
const ctx = {};
|
|
30250
|
+
if (!roleRecordUsable) ctx.ignoreStateForRoles = true;
|
|
31194
30251
|
let stateRecordRegion;
|
|
31195
30252
|
const wantsPseudoForEnvOrSecret = !!stateProvider && needs.needsEnvOrSecretSubstitution;
|
|
31196
30253
|
if (needs.needsPseudoParameters || wantsPseudoForEnvOrSecret) {
|
|
@@ -31217,7 +30274,7 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
|
|
|
31217
30274
|
}
|
|
31218
30275
|
};
|
|
31219
30276
|
}
|
|
31220
|
-
const wantsState = needs.needsStateResources || needs.needsEnvOrSecretSubstitution;
|
|
30277
|
+
const wantsState = needs.needsStateResources || needs.needsEnvOrSecretSubstitution || wantsStateForTaskRole;
|
|
31221
30278
|
if (stateProvider && wantsState) {
|
|
31222
30279
|
const loaded = await stateProvider.load(candidate.stackName, candidate.region);
|
|
31223
30280
|
if (loaded) {
|
|
@@ -31245,6 +30302,9 @@ async function buildEcsImageResolutionContext$1(candidate, stateProvider, option
|
|
|
31245
30302
|
...stateRecordRegion !== void 0 && { stateRecordRegion }
|
|
31246
30303
|
};
|
|
31247
30304
|
}
|
|
30305
|
+
function taskRoleRecordIsEmulatorSide() {
|
|
30306
|
+
return getActiveWorkloadAwsWiring$1()?.mixed !== void 0 && !realAwsException("IAM");
|
|
30307
|
+
}
|
|
31248
30308
|
function pickCandidateStack(parsed, target, stacks) {
|
|
31249
30309
|
const byPrefix = stackForPathFormTarget(parsed, target, stacks);
|
|
31250
30310
|
if (byPrefix) return byPrefix;
|
|
@@ -31278,26 +30338,48 @@ function readEnvOverridesFile$2(filePath) {
|
|
|
31278
30338
|
}
|
|
31279
30339
|
|
|
31280
30340
|
// src/cli/commands/local-run-task/credentials.ts
|
|
31281
|
-
async function resolveSidecarCredentials(options, assumedCredentials) {
|
|
30341
|
+
async function resolveSidecarCredentials(options, assumedCredentials, emulatorTaskCredentials) {
|
|
31282
30342
|
const wiring = getActiveWorkloadAwsWiring();
|
|
31283
|
-
if (wiring?.mode === "emulator"
|
|
31284
|
-
|
|
30343
|
+
if (wiring?.mode === "emulator" || wiring?.mixed) {
|
|
30344
|
+
if (emulatorTaskCredentials) return emulatorTaskCredentials;
|
|
30345
|
+
return wiring.mode === "emulator" ? wiring.emulatorCredentials : wiring.mixed?.emulatorCredentials;
|
|
30346
|
+
}
|
|
31285
30347
|
if (assumedCredentials) return assumedCredentials;
|
|
31286
30348
|
if (options.profile) return resolveProfileCredentials(options.profile);
|
|
31287
30349
|
return resolveHostDefaultCredentials();
|
|
31288
30350
|
}
|
|
30351
|
+
function planTaskRoleCredentials(containers, envOverrides, roleRequested) {
|
|
30352
|
+
const wiring = getActiveWorkloadAwsWiring();
|
|
30353
|
+
const envs = containers.map((c) => previewContainerEnv(c, envOverrides));
|
|
30354
|
+
const realSts = envs.map((env) => taskRoleAssumedInRealAws(env, wiring));
|
|
30355
|
+
const assumeInRealAws = roleRequested && realSts.some((r) => r);
|
|
30356
|
+
return {
|
|
30357
|
+
assumeInRealAws,
|
|
30358
|
+
assumeInEmulator: roleRequested && wiring?.mode === "emulator",
|
|
30359
|
+
ignoredInMixedMode: roleRequested && wiring?.mixed !== void 0 && !assumeInRealAws,
|
|
30360
|
+
callerIdentityNeeded: envs.some((env, i) => !workloadGetsEmulatorKeysOnly(env, wiring) && !(assumeInRealAws && realSts[i]))
|
|
30361
|
+
};
|
|
30362
|
+
}
|
|
31289
30363
|
async function resolveTaskCredentialChannels(options, assumedCredentials, opts) {
|
|
31290
|
-
const
|
|
30364
|
+
const emulatorTaskCredentials = opts?.emulatorTaskCredentials;
|
|
30365
|
+
const sidecarCredentials = await resolveSidecarCredentials(options, assumedCredentials, emulatorTaskCredentials);
|
|
30366
|
+
const emulatorTask = emulatorTaskCredentials && { emulatorTaskCredentials };
|
|
31291
30367
|
if (getActiveWorkloadAwsWiring()?.mixed) {
|
|
31292
|
-
const
|
|
30368
|
+
const caller = opts?.callerIdentityNeeded === false ? void 0 : options.profile ? await resolveProfileCredentials(options.profile) : await resolveHostDefaultCredentials();
|
|
31293
30369
|
return {
|
|
31294
30370
|
sidecarCredentials,
|
|
31295
30371
|
profileCredsFile: void 0,
|
|
31296
|
-
...
|
|
30372
|
+
...caller && { mixedModeRealCredentials: caller },
|
|
30373
|
+
...assumedCredentials && { mixedModeRealTaskCredentials: assumedCredentials },
|
|
30374
|
+
...emulatorTask
|
|
31297
30375
|
};
|
|
31298
30376
|
}
|
|
31299
|
-
|
|
31300
|
-
|
|
30377
|
+
if (getActiveWorkloadAwsWiring()?.mode === "emulator") return {
|
|
30378
|
+
sidecarCredentials,
|
|
30379
|
+
profileCredsFile: void 0,
|
|
30380
|
+
...emulatorTask
|
|
30381
|
+
};
|
|
30382
|
+
if (options.profile && sidecarCredentials && !assumedCredentials) return {
|
|
31301
30383
|
sidecarCredentials,
|
|
31302
30384
|
profileCredsFile: await writeProfileCredentialsFile(options.profile, sidecarCredentials, opts)
|
|
31303
30385
|
};
|
|
@@ -31317,6 +30399,8 @@ function buildRunEcsTaskOptions(options, channels, extra = {}) {
|
|
|
31317
30399
|
if (extra.envOverrides) runOpts.envOverrides = extra.envOverrides;
|
|
31318
30400
|
if (channels.sidecarCredentials) runOpts.taskCredentials = channels.sidecarCredentials;
|
|
31319
30401
|
if (channels.mixedModeRealCredentials) runOpts.mixedModeRealCredentials = channels.mixedModeRealCredentials;
|
|
30402
|
+
if (channels.mixedModeRealTaskCredentials) runOpts.mixedModeRealTaskCredentials = channels.mixedModeRealTaskCredentials;
|
|
30403
|
+
if (channels.emulatorTaskCredentials) runOpts.emulatorTaskCredentials = channels.emulatorTaskCredentials;
|
|
31320
30404
|
if (extra.resolvedRoleArn) runOpts.taskRoleArn = extra.resolvedRoleArn;
|
|
31321
30405
|
if (options.platform) runOpts.platformOverride = options.platform;
|
|
31322
30406
|
if (options.region) runOpts.region = options.region;
|
|
@@ -31432,6 +30516,10 @@ async function localRunTaskCommand(target, options) {
|
|
|
31432
30516
|
try {
|
|
31433
30517
|
if (typeof options.assumeTaskRole === "string") assertFlagRoleArn("--assume-task-role", options.assumeTaskRole);
|
|
31434
30518
|
if (options.ecrRoleArn !== void 0) assertFlagRoleArn("--ecr-role-arn", options.ecrRoleArn);
|
|
30519
|
+
checkEmulateRoleVia(options.emulateRoleVia, {
|
|
30520
|
+
roleFlag: "--assume-task-role",
|
|
30521
|
+
roleRequested: options.assumeTaskRole === true || typeof options.assumeTaskRole === "string"
|
|
30522
|
+
});
|
|
31435
30523
|
await activateLocalAwsAndRoleArn(options);
|
|
31436
30524
|
await ensureDockerAvailable();
|
|
31437
30525
|
const appCmd = resolveApp(options.app);
|
|
@@ -31497,15 +30585,26 @@ async function localRunTaskCommand(target, options) {
|
|
|
31497
30585
|
cleanup().then(() => process.exit(130));
|
|
31498
30586
|
};
|
|
31499
30587
|
process.on("SIGINT", sigintHandler);
|
|
30588
|
+
const envOverrides = readEnvOverridesFile$2(options.envVars);
|
|
30589
|
+
const roleRequested = options.assumeTaskRole === true || typeof options.assumeTaskRole === "string";
|
|
30590
|
+
const plan = planTaskRoleCredentials(task.containers, envOverrides, roleRequested);
|
|
30591
|
+
if (plan.ignoredInMixedMode) logger.warn("--assume-task-role has no effect in AWS Emulator mixed mode unless a container marks STS as an exception (AWS_ENDPOINT_URL_STS=\"real-aws\"): calls to the emulator are re-signed with the emulator's keys, so the role is not assumed.");
|
|
31500
30592
|
let assumedCredentials;
|
|
30593
|
+
let emulatorTaskCredentials;
|
|
31501
30594
|
let resolvedRoleArn;
|
|
31502
|
-
|
|
31503
|
-
|
|
31504
|
-
|
|
31505
|
-
|
|
31506
|
-
|
|
31507
|
-
|
|
31508
|
-
|
|
30595
|
+
const assumes = plan.assumeInRealAws || plan.assumeInEmulator;
|
|
30596
|
+
if (options.assumeTaskRole === true && !task.taskRoleArn && assumes) throw new Error("--assume-task-role passed without an ARN but the task definition has no resolvable TaskRoleArn. Either the task definition does not set TaskRoleArn, or it points at a resource cdkd cannot resolve to an IAM Role at synth time. Pass the ARN explicitly: --assume-task-role '<arn>'");
|
|
30597
|
+
const roleArnTemplate = options.assumeTaskRole === true ? task.taskRoleArn : typeof options.assumeTaskRole === "string" ? options.assumeTaskRole : void 0;
|
|
30598
|
+
if (roleArnTemplate !== void 0 && assumes) {
|
|
30599
|
+
const realAws = plan.assumeInRealAws;
|
|
30600
|
+
if (options.assumeTaskRole === true && task.taskRoleUnresolved !== void 0) {
|
|
30601
|
+
const { logicalId, reason } = task.taskRoleUnresolved;
|
|
30602
|
+
logger.warn(taskRoleNameIsLogicalIdWarning(logicalId, !stateProvider ? "no-state-source" : taskRoleRecordIsEmulatorSide() ? "mixed-mode-emulator-iam" : reason === "no-state" ? "state-not-read" : reason));
|
|
30603
|
+
}
|
|
30604
|
+
resolvedRoleArn = options.assumeTaskRole === true ? await resolvePlaceholderAccount(roleArnTemplate, options, { realAws }) : roleArnTemplate;
|
|
30605
|
+
const creds = await assumeTaskRole(resolvedRoleArn, options.region, { realAws }, options.emulateRoleVia);
|
|
30606
|
+
if (realAws) assumedCredentials = creds;
|
|
30607
|
+
else emulatorTaskCredentials = creds;
|
|
31509
30608
|
}
|
|
31510
30609
|
channels = await resolveTaskCredentialChannels(options, assumedCredentials, {
|
|
31511
30610
|
onDirCreated: (hostPath) => {
|
|
@@ -31513,9 +30612,10 @@ async function localRunTaskCommand(target, options) {
|
|
|
31513
30612
|
},
|
|
31514
30613
|
onDirRemoved: () => {
|
|
31515
30614
|
credsHostPath = void 0;
|
|
31516
|
-
}
|
|
30615
|
+
},
|
|
30616
|
+
emulatorTaskCredentials,
|
|
30617
|
+
callerIdentityNeeded: plan.callerIdentityNeeded
|
|
31517
30618
|
});
|
|
31518
|
-
const envOverrides = readEnvOverridesFile$2(options.envVars);
|
|
31519
30619
|
const runOpts = buildRunEcsTaskOptions(options, channels, {
|
|
31520
30620
|
...envOverrides !== void 0 && { envOverrides },
|
|
31521
30621
|
...resolvedRoleArn !== void 0 && { resolvedRoleArn },
|
|
@@ -31588,7 +30688,7 @@ async function applyPerContainerNames(task, target, stacks, candidate, options,
|
|
|
31588
30688
|
|
|
31589
30689
|
// src/cli/commands/local-run-task.ts
|
|
31590
30690
|
function createLocalRunTaskCommand() {
|
|
31591
|
-
const cmd = new Command("run-task").description("Run an AWS::ECS::TaskDefinition locally — pulls/builds images, sets up a per-task docker network with the AWS-published metadata-endpoints sidecar, and starts every container in dependsOn order. Target accepts a CDK display path (MyStack/MyService/TaskDef) or stack-qualified logical ID (MyStack:MyServiceTaskDefXYZ1234). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the AWS::ECS::TaskDefinition to run").addOption(new Option("--cluster <name>", "Cluster name surfaced to ECS_CONTAINER_METADATA_URI_V4 and used as the docker network prefix").default("cdkd-local")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"ContainerName\":{\"KEY\":\"VALUE\"}, \"Parameters\":{}})")).addOption(new Option("--container-host <ip>", "Host IP to bind published container ports to. Must be a numeric IP (Docker rejects hostnames here)").default("127.0.0.1")).addOption(new Option("--assume-task-role [arn]", "Assume the task definition's TaskRoleArn (or the supplied ARN) and forward STS-issued temp credentials via the metadata sidecar so containers run with the deployed function role. Bare flag uses the template's TaskRoleArn; pass an explicit ARN to override.")).addOption(new Option("--no-pull", "Skip docker pull for every container image and the metadata sidecar")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--platform <platform>", "Force docker --platform (linux/amd64 or linux/arm64). Default: inferred from task RuntimePlatform.CpuArchitecture")).addOption(new Option("--keep-running", "Don't docker rm -f the user containers on task exit (network + sidecar are still torn down). Use when you want to docker exec into a stopped container for post-mortems.").default(false)).addOption(new Option("--detach", "Start the containers in the background and exit (skip log streaming + auto teardown). Useful in CI smoke tests; caller manages container lifecycle.").default(false)).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Fn::Sub / Fn::GetAtt references to same-stack AWS::ECR::Repository resources with the deployed URI. Off by default — only the AWS pseudo-parameter tier (${AWS::AccountId} / ${AWS::Region}) is resolved without this flag.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in container env vars / secrets / image URIs with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localRunTaskCommand));
|
|
30691
|
+
const cmd = new Command("run-task").description("Run an AWS::ECS::TaskDefinition locally — pulls/builds images, sets up a per-task docker network with the AWS-published metadata-endpoints sidecar, and starts every container in dependsOn order. Target accepts a CDK display path (MyStack/MyService/TaskDef) or stack-qualified logical ID (MyStack:MyServiceTaskDefXYZ1234). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the AWS::ECS::TaskDefinition to run").addOption(new Option("--cluster <name>", "Cluster name surfaced to ECS_CONTAINER_METADATA_URI_V4 and used as the docker network prefix").default("cdkd-local")).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"ContainerName\":{\"KEY\":\"VALUE\"}, \"Parameters\":{}})")).addOption(new Option("--container-host <ip>", "Host IP to bind published container ports to. Must be a numeric IP (Docker rejects hostnames here)").default("127.0.0.1")).addOption(new Option("--assume-task-role [arn]", "Assume the task definition's TaskRoleArn (or the supplied ARN) and forward STS-issued temp credentials via the metadata sidecar so containers run with the deployed function role. Bare flag uses the template's TaskRoleArn; pass an explicit ARN to override.")).addOption(emulateRoleViaOption("--assume-task-role")).addOption(new Option("--no-pull", "Skip docker pull for every container image and the metadata sidecar")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--platform <platform>", "Force docker --platform (linux/amd64 or linux/arm64). Default: inferred from task RuntimePlatform.CpuArchitecture")).addOption(new Option("--keep-running", "Don't docker rm -f the user containers on task exit (network + sidecar are still torn down). Use when you want to docker exec into a stopped container for post-mortems.").default(false)).addOption(new Option("--detach", "Start the containers in the background and exit (skip log streaming + auto teardown). Useful in CI smoke tests; caller manages container lifecycle.").default(false)).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Fn::Sub / Fn::GetAtt references to same-stack AWS::ECR::Repository resources with the deployed URI. Off by default — only the AWS pseudo-parameter tier (${AWS::AccountId} / ${AWS::Region}) is resolved without this flag.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in container env vars / secrets / image URIs with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localRunTaskCommand));
|
|
31592
30692
|
addImageOverrideOptions(cmd);
|
|
31593
30693
|
[
|
|
31594
30694
|
...commonOptions,
|
|
@@ -32016,7 +31116,11 @@ async function buildContainerEnvWith(resolved, options, profileCredentials, prof
|
|
|
32016
31116
|
const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
|
|
32017
31117
|
await applyAgentCoreCredentialEnv(dockerEnv, {
|
|
32018
31118
|
...assumeRoleArn !== void 0 && { assumeRoleArn },
|
|
31119
|
+
...options.emulateRoleVia !== void 0 && { emulateRoleVia: options.emulateRoleVia },
|
|
32019
31120
|
...options.region !== void 0 && { region: options.region },
|
|
31121
|
+
...resolved.stack.region !== void 0 && { stackRegion: resolved.stack.region },
|
|
31122
|
+
...loaded?.region !== void 0 && { stateRegion: loaded.region },
|
|
31123
|
+
...options.profile !== void 0 && { profile: options.profile },
|
|
32020
31124
|
...profileCredentials !== void 0 && { profileCredentials },
|
|
32021
31125
|
...profileCredsFile !== void 0 && { profileCredsFile: {
|
|
32022
31126
|
containerPath: profileCredsFile.containerPath,
|
|
@@ -32057,10 +31161,16 @@ async function resolveStackAccountId(region, profile, fromState, fromCfnStack) {
|
|
|
32057
31161
|
async function applyAgentCoreCredentialEnv(dockerEnv, args) {
|
|
32058
31162
|
const logger = getLogger();
|
|
32059
31163
|
let assumeSucceeded = false;
|
|
31164
|
+
const containerRegion = await resolveContainerRegion({
|
|
31165
|
+
region: args.region,
|
|
31166
|
+
stackRegion: args.stackRegion,
|
|
31167
|
+
stateRegion: args.stateRegion,
|
|
31168
|
+
profile: args.profile
|
|
31169
|
+
});
|
|
32060
31170
|
if (args.assumeRoleArn) {
|
|
32061
|
-
const stsRegion =
|
|
31171
|
+
const stsRegion = containerRegion;
|
|
32062
31172
|
try {
|
|
32063
|
-
const creds = await assumeAgentCoreExecutionRole(args.assumeRoleArn, stsRegion);
|
|
31173
|
+
const creds = await assumeAgentCoreExecutionRole(args.assumeRoleArn, stsRegion, args.emulateRoleVia);
|
|
32064
31174
|
dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
|
|
32065
31175
|
dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
|
|
32066
31176
|
dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
|
|
@@ -32072,7 +31182,7 @@ async function applyAgentCoreCredentialEnv(dockerEnv, args) {
|
|
|
32072
31182
|
}
|
|
32073
31183
|
if (!assumeSucceeded) {
|
|
32074
31184
|
forwardAwsEnv$1(dockerEnv);
|
|
32075
|
-
setContainerRegion(dockerEnv,
|
|
31185
|
+
setContainerRegion(dockerEnv, containerRegion);
|
|
32076
31186
|
applyProfileCredentialsOverlay(dockerEnv, args.profileCredentials, false);
|
|
32077
31187
|
if (args.profileCredsFile) {
|
|
32078
31188
|
dockerEnv["AWS_SHARED_CREDENTIALS_FILE"] = args.profileCredsFile.containerPath;
|
|
@@ -32125,7 +31235,7 @@ function forwardAwsEnv$1(env) {
|
|
|
32125
31235
|
}
|
|
32126
31236
|
applyCallerIdentityCredentials(env);
|
|
32127
31237
|
}
|
|
32128
|
-
async function assumeAgentCoreExecutionRole(roleArn, region) {
|
|
31238
|
+
async function assumeAgentCoreExecutionRole(roleArn, region, emulateRoleVia) {
|
|
32129
31239
|
assertSendableRoleArn(roleArn, (m) => new CdkdError(m, "LOCAL_INVOKE_AGENTCORE_ASSUME_ROLE_INVALID"));
|
|
32130
31240
|
const { STSClient } = await import("@aws-sdk/client-sts");
|
|
32131
31241
|
const sts = new STSClient({
|
|
@@ -32136,11 +31246,26 @@ async function assumeAgentCoreExecutionRole(roleArn, region) {
|
|
|
32136
31246
|
...region && { region }
|
|
32137
31247
|
});
|
|
32138
31248
|
try {
|
|
32139
|
-
|
|
32140
|
-
|
|
32141
|
-
|
|
32142
|
-
|
|
32143
|
-
|
|
31249
|
+
let response;
|
|
31250
|
+
try {
|
|
31251
|
+
response = await sts.send(sendableAssumeRoleCommand({
|
|
31252
|
+
RoleArn: roleArn,
|
|
31253
|
+
RoleSessionName: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore-${Date.now()}`,
|
|
31254
|
+
DurationSeconds: 3600
|
|
31255
|
+
}));
|
|
31256
|
+
} catch (err) {
|
|
31257
|
+
const emulated = await emulateRoleAfterDeniedAssume(err, {
|
|
31258
|
+
roleArn,
|
|
31259
|
+
region,
|
|
31260
|
+
realAws: mixedModeActive(),
|
|
31261
|
+
...emulateRoleVia !== void 0 && { emulateRoleVia },
|
|
31262
|
+
flag: "--assume-role",
|
|
31263
|
+
sessionNamePrefix: `${getEmbedConfig().resourceNamePrefix}-invoke-agentcore`
|
|
31264
|
+
});
|
|
31265
|
+
if (emulated) return emulated;
|
|
31266
|
+
throw err;
|
|
31267
|
+
}
|
|
31268
|
+
const creds = response.Credentials;
|
|
32144
31269
|
if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_INVOKE_AGENTCORE_ASSUMEROLE_NO_CREDS");
|
|
32145
31270
|
return {
|
|
32146
31271
|
accessKeyId: creds.AccessKeyId,
|
|
@@ -32237,7 +31362,11 @@ async function resolveAgentCoreImage(resolved, options, assemblyDir, loaded) {
|
|
|
32237
31362
|
if (entry) return buildContainerImage$1(entry.asset, cdkOutDir, {
|
|
32238
31363
|
assetOutdir: assemblyDir,
|
|
32239
31364
|
architecture,
|
|
32240
|
-
noBuild: options.build === false
|
|
31365
|
+
noBuild: options.build === false,
|
|
31366
|
+
workload: {
|
|
31367
|
+
logicalId: resolved.logicalId,
|
|
31368
|
+
cdkPath: readCdkPathOrUndefined(resolved.resource)
|
|
31369
|
+
}
|
|
32241
31370
|
});
|
|
32242
31371
|
}
|
|
32243
31372
|
}
|
|
@@ -32292,7 +31421,7 @@ async function resolveAgentCoreCodeImageFromS3(resolved, code, s3Source, options
|
|
|
32292
31421
|
const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
|
|
32293
31422
|
let credentials;
|
|
32294
31423
|
if (assumeRoleArn) try {
|
|
32295
|
-
credentials = await assumeAgentCoreExecutionRole(assumeRoleArn, region);
|
|
31424
|
+
credentials = await assumeAgentCoreExecutionRole(assumeRoleArn, region, options.emulateRoleVia);
|
|
32296
31425
|
} catch (err) {
|
|
32297
31426
|
logger.warn(assumeRoleFallbackWarning({
|
|
32298
31427
|
assumeRoleArn,
|
|
@@ -32539,7 +31668,7 @@ async function resolveHostCredentialsForSigV4(options, resolved, loaded, region)
|
|
|
32539
31668
|
};
|
|
32540
31669
|
const assumeRoleArn = resolveAssumeRoleArn(options, resolved, loaded);
|
|
32541
31670
|
if (assumeRoleArn) try {
|
|
32542
|
-
return await assumeAgentCoreExecutionRole(assumeRoleArn, region);
|
|
31671
|
+
return await assumeAgentCoreExecutionRole(assumeRoleArn, region, options.emulateRoleVia);
|
|
32543
31672
|
} catch (err) {
|
|
32544
31673
|
logger.warn(assumeRoleFallbackWarning({
|
|
32545
31674
|
assumeRoleArn,
|
|
@@ -32654,6 +31783,10 @@ async function localInvokeAgentCoreCommand(target, options) {
|
|
|
32654
31783
|
try {
|
|
32655
31784
|
if (typeof options.assumeRole === "string") explicitRoleArnOrThrow("--assume-role", options.assumeRole, (message) => new CdkdError(message, "LOCAL_INVOKE_AGENTCORE_ASSUME_ROLE_INVALID"));
|
|
32656
31785
|
if (options.ecrRoleArn !== void 0) assertFlagRoleArn("--ecr-role-arn", options.ecrRoleArn, (message) => new CdkdError(message, "LOCAL_INVOKE_AGENTCORE_ECR_ROLE_ARN_INVALID"));
|
|
31786
|
+
checkEmulateRoleVia(options.emulateRoleVia, {
|
|
31787
|
+
roleFlag: "--assume-role",
|
|
31788
|
+
roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
|
|
31789
|
+
});
|
|
32657
31790
|
await activateLocalAwsAndRoleArn(options);
|
|
32658
31791
|
await ensureDockerAvailable();
|
|
32659
31792
|
const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
|
|
@@ -32895,7 +32028,7 @@ function parseTimeoutMs(raw) {
|
|
|
32895
32028
|
return parsed;
|
|
32896
32029
|
}
|
|
32897
32030
|
function createLocalInvokeAgentCoreCommand() {
|
|
32898
|
-
const cmd = new Command("invoke-agentcore").description("Run a Bedrock AgentCore Runtime container locally and invoke it once over its protocol contract: HTTP (POST /invocations + GET /ping on 8080) or MCP (POST /mcp Streamable HTTP on 8000). Resolves the AWS::BedrockAgentCore::Runtime, pulls/builds its container, injects env vars + AWS credentials, and prints the response. For an MCP runtime, runs the session handshake then sends one JSON-RPC request (tools/list by default, or the method/params from --event). Target accepts a CDK display path (MyStack/MyAgent) or stack-qualified logical ID (MyStack:MyAgentRuntime1234). Single-stack apps may omit the stack prefix. Omit <target> in an interactive terminal to pick from a list. Supports the container artifact and the CodeConfiguration managed-runtime artifact (fromCodeAsset, built from source) on the HTTP + MCP protocols; the agent calls real AWS for managed services.").argument("[target]", "CDK display path or stack-qualified logical ID of the AgentCore Runtime to invoke (omit to pick interactively in a TTY)").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--session-id <id>", "AgentCore runtime session id header value (default: a random UUID)")).addOption(new Option("--ws", "Stream over the HTTP-protocol agent's bidirectional /ws WebSocket endpoint (on 8080) instead of POST /invocations: send --event as the first frame and print every received frame to stdout until the agent closes. When stdin is a TTY, auto-enters a REPL — each typed line is sent as a follow-up text frame until Ctrl-D / agent close; pipe from /dev/null to force one-shot in a TTY. Ignored for an MCP runtime.").default(false)).addOption(new Option("--watch", "Re-synth and reload the agent container on CDK source changes. Supported on the HTTP / AGUI protocols, both the --ws session AND the default one-shot POST /invocations (the reload re-runs the single shot). An interpreted-language source edit inside a CodeConfiguration source tree takes a soft-reload fast path (docker cp + docker restart, no rebuild); Dockerfile / compiled-source / asset-hash-changed / ambiguous edits force a full rebuild. For MCP / A2A runtimes --watch is a no-op WARN and the single shot proceeds.").default(false)).addOption(new Option("--bearer-token <jwt>", "Bearer JWT to present when the runtime declares a customJwtAuthorizer. Verified against the runtime OIDC discovery URL (signature / issuer / expiry / audience) before the container starts, then forwarded to /invocations as Authorization: Bearer <jwt>.")).addOption(new Option("--no-verify-auth", "Skip inbound JWT verification even when the runtime declares a customJwtAuthorizer (local-dev escape hatch). A --bearer-token, if given, is still forwarded.")).addOption(new Option("--sigv4", "Sign the /invocations POST with AWS SigV4 (service bedrock-agentcore) using the resolved credentials, matching the cloud default when the runtime declares no customJwtAuthorizer. Opt-in: default unsigned. Mutually exclusive with --bearer-token; ignored on a JWT-protected runtime.").default(false)).addOption(new Option("--platform <platform>", "docker --platform for the agent container (linux/amd64 or linux/arm64)").choices(["linux/amd64", "linux/arm64"]).default("linux/arm64")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for the local-build path")).addOption(new Option("--no-build", "Skip docker build on the local-asset path (use the previously-built tag). No-op for the ECR / registry pull paths.")).addOption(new Option("--container-host <host>", "Host to bind the agent port to").default("127.0.0.1")).addOption(new Option("--timeout <ms>", "Per-request timeout in milliseconds. Applied to POST /invocations, POST /mcp, and the /ws open-to-close window. Raise this for long-running agent calls that exceed the default.").default(12e4).argParser(parseTimeoutMs)).addOption(new Option("--assume-role [arn]", "Assume the runtime's execution role and forward STS-issued temp credentials to the container so the agent runs with the deployed role. Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) uses the runtime's RoleArn when it is a literal ARN; (3) `--no-assume-role` opts out. Off by default — the developer's shell credentials are forwarded unchanged.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the runtime's execution role: forward your ambient AWS credentials (or the --profile overlay) unchanged even when --from-state / --from-cfn-stack is set.")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Load cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue in env vars with the deployed physical IDs / cross-stack exports. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. For CDK apps deployed via the upstream CDK CLI. Bare form uses the resolved stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state.")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-cfn-stack as the CFn client region.").argParser(parseStackRegion)).action(withErrorHandling(async (target, options) => {
|
|
32031
|
+
const cmd = new Command("invoke-agentcore").description("Run a Bedrock AgentCore Runtime container locally and invoke it once over its protocol contract: HTTP (POST /invocations + GET /ping on 8080) or MCP (POST /mcp Streamable HTTP on 8000). Resolves the AWS::BedrockAgentCore::Runtime, pulls/builds its container, injects env vars + AWS credentials, and prints the response. For an MCP runtime, runs the session handshake then sends one JSON-RPC request (tools/list by default, or the method/params from --event). Target accepts a CDK display path (MyStack/MyAgent) or stack-qualified logical ID (MyStack:MyAgentRuntime1234). Single-stack apps may omit the stack prefix. Omit <target> in an interactive terminal to pick from a list. Supports the container artifact and the CodeConfiguration managed-runtime artifact (fromCodeAsset, built from source) on the HTTP + MCP protocols; the agent calls real AWS for managed services.").argument("[target]", "CDK display path or stack-qualified logical ID of the AgentCore Runtime to invoke (omit to pick interactively in a TTY)").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--session-id <id>", "AgentCore runtime session id header value (default: a random UUID)")).addOption(new Option("--ws", "Stream over the HTTP-protocol agent's bidirectional /ws WebSocket endpoint (on 8080) instead of POST /invocations: send --event as the first frame and print every received frame to stdout until the agent closes. When stdin is a TTY, auto-enters a REPL — each typed line is sent as a follow-up text frame until Ctrl-D / agent close; pipe from /dev/null to force one-shot in a TTY. Ignored for an MCP runtime.").default(false)).addOption(new Option("--watch", "Re-synth and reload the agent container on CDK source changes. Supported on the HTTP / AGUI protocols, both the --ws session AND the default one-shot POST /invocations (the reload re-runs the single shot). An interpreted-language source edit inside a CodeConfiguration source tree takes a soft-reload fast path (docker cp + docker restart, no rebuild); Dockerfile / compiled-source / asset-hash-changed / ambiguous edits force a full rebuild. For MCP / A2A runtimes --watch is a no-op WARN and the single shot proceeds.").default(false)).addOption(new Option("--bearer-token <jwt>", "Bearer JWT to present when the runtime declares a customJwtAuthorizer. Verified against the runtime OIDC discovery URL (signature / issuer / expiry / audience) before the container starts, then forwarded to /invocations as Authorization: Bearer <jwt>.")).addOption(new Option("--no-verify-auth", "Skip inbound JWT verification even when the runtime declares a customJwtAuthorizer (local-dev escape hatch). A --bearer-token, if given, is still forwarded.")).addOption(new Option("--sigv4", "Sign the /invocations POST with AWS SigV4 (service bedrock-agentcore) using the resolved credentials, matching the cloud default when the runtime declares no customJwtAuthorizer. Opt-in: default unsigned. Mutually exclusive with --bearer-token; ignored on a JWT-protected runtime.").default(false)).addOption(new Option("--platform <platform>", "docker --platform for the agent container (linux/amd64 or linux/arm64)").choices(["linux/amd64", "linux/arm64"]).default("linux/arm64")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for the local-build path")).addOption(new Option("--no-build", "Skip docker build on the local-asset path (use the previously-built tag). No-op for the ECR / registry pull paths.")).addOption(new Option("--container-host <host>", "Host to bind the agent port to").default("127.0.0.1")).addOption(new Option("--timeout <ms>", "Per-request timeout in milliseconds. Applied to POST /invocations, POST /mcp, and the /ws open-to-close window. Raise this for long-running agent calls that exceed the default.").default(12e4).argParser(parseTimeoutMs)).addOption(new Option("--assume-role [arn]", "Assume the runtime's execution role and forward STS-issued temp credentials to the container so the agent runs with the deployed role. Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) uses the runtime's RoleArn when it is a literal ARN; (3) `--no-assume-role` opts out. Off by default — the developer's shell credentials are forwarded unchanged.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the runtime's execution role: forward your ambient AWS credentials (or the --profile overlay) unchanged even when --from-state / --from-cfn-stack is set.")).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Load cdkd's S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub / Fn::ImportValue in env vars with the deployed physical IDs / cross-stack exports. Mutually exclusive with --from-cfn-stack.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. For CDK apps deployed via the upstream CDK CLI. Bare form uses the resolved stack name; pass an explicit value when the CFn stack name differs. Mutually exclusive with --from-state.")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-cfn-stack as the CFn client region.").argParser(parseStackRegion)).action(withErrorHandling(async (target, options) => {
|
|
32899
32032
|
await localInvokeAgentCoreCommand(target, options);
|
|
32900
32033
|
}));
|
|
32901
32034
|
[
|
|
@@ -32977,18 +32110,21 @@ function createLocalStartMicrovmCommand$1() {
|
|
|
32977
32110
|
async function applyLambdaCredentialEnv(dockerEnv, args) {
|
|
32978
32111
|
const logger = getLogger();
|
|
32979
32112
|
let assumeSucceeded = false;
|
|
32980
|
-
|
|
32981
|
-
|
|
32982
|
-
|
|
32983
|
-
|
|
32984
|
-
|
|
32985
|
-
|
|
32986
|
-
|
|
32987
|
-
|
|
32988
|
-
|
|
32989
|
-
|
|
32990
|
-
|
|
32991
|
-
|
|
32113
|
+
const containerRegion = await resolveContainerRegion({
|
|
32114
|
+
region: args.region,
|
|
32115
|
+
stackRegion: args.stackRegion,
|
|
32116
|
+
stateRegion: args.stateRegion,
|
|
32117
|
+
profile: args.profile
|
|
32118
|
+
});
|
|
32119
|
+
if (args.assumeRoleArn) try {
|
|
32120
|
+
const creds = await assumeLambdaExecutionRole(args.assumeRoleArn, containerRegion, args.emulateRoleVia);
|
|
32121
|
+
dockerEnv["AWS_ACCESS_KEY_ID"] = creds.accessKeyId;
|
|
32122
|
+
dockerEnv["AWS_SECRET_ACCESS_KEY"] = creds.secretAccessKey;
|
|
32123
|
+
dockerEnv["AWS_SESSION_TOKEN"] = creds.sessionToken;
|
|
32124
|
+
setContainerRegion(dockerEnv, containerRegion);
|
|
32125
|
+
assumeSucceeded = true;
|
|
32126
|
+
} catch (err) {
|
|
32127
|
+
logger.warn(`--assume-role: STS AssumeRole(${displayIdent(args.assumeRoleArn, { maxCodePoints: 613 })}) failed: ${describeLocalAwsFailureForWarn(err, "STS AssumeRole")}. Falling back to the developer's shell credentials.`);
|
|
32992
32128
|
}
|
|
32993
32129
|
if (!assumeSucceeded) {
|
|
32994
32130
|
forwardAwsEnv(dockerEnv);
|
|
@@ -32997,11 +32133,10 @@ async function applyLambdaCredentialEnv(dockerEnv, args) {
|
|
|
32997
32133
|
dockerEnv["AWS_SHARED_CREDENTIALS_FILE"] = args.profileCredsFile.containerPath;
|
|
32998
32134
|
dockerEnv["AWS_PROFILE"] = args.profileCredsFile.profileName;
|
|
32999
32135
|
}
|
|
33000
|
-
const containerRegion = firstUsableRegion(args.region, process.env["AWS_REGION"], process.env["AWS_DEFAULT_REGION"], args.stackRegion);
|
|
33001
32136
|
setContainerRegion(dockerEnv, containerRegion);
|
|
33002
32137
|
}
|
|
33003
32138
|
}
|
|
33004
|
-
async function assumeLambdaExecutionRole(roleArn, region) {
|
|
32139
|
+
async function assumeLambdaExecutionRole(roleArn, region, emulateRoleVia) {
|
|
33005
32140
|
assertSendableRoleArn(roleArn, (m) => new CdkdError(m, "LOCAL_INVOKE_ASSUME_ROLE_INVALID"));
|
|
33006
32141
|
const { STSClient } = await import("@aws-sdk/client-sts");
|
|
33007
32142
|
const sts = new STSClient({
|
|
@@ -33012,11 +32147,26 @@ async function assumeLambdaExecutionRole(roleArn, region) {
|
|
|
33012
32147
|
...region && { region }
|
|
33013
32148
|
});
|
|
33014
32149
|
try {
|
|
33015
|
-
|
|
33016
|
-
|
|
33017
|
-
|
|
33018
|
-
|
|
33019
|
-
|
|
32150
|
+
let response;
|
|
32151
|
+
try {
|
|
32152
|
+
response = await sts.send(sendableAssumeRoleCommand({
|
|
32153
|
+
RoleArn: roleArn,
|
|
32154
|
+
RoleSessionName: `cdkd-local-invoke-${Date.now()}`,
|
|
32155
|
+
DurationSeconds: 3600
|
|
32156
|
+
}));
|
|
32157
|
+
} catch (err) {
|
|
32158
|
+
const emulated = await emulateRoleAfterDeniedAssume(err, {
|
|
32159
|
+
roleArn,
|
|
32160
|
+
region,
|
|
32161
|
+
realAws: mixedModeActive(),
|
|
32162
|
+
...emulateRoleVia !== void 0 && { emulateRoleVia },
|
|
32163
|
+
flag: "--assume-role",
|
|
32164
|
+
sessionNamePrefix: "cdkd-local-invoke"
|
|
32165
|
+
});
|
|
32166
|
+
if (emulated) return emulated;
|
|
32167
|
+
throw err;
|
|
32168
|
+
}
|
|
32169
|
+
const creds = response.Credentials;
|
|
33020
32170
|
if (!creds?.AccessKeyId || !creds.SecretAccessKey || !creds.SessionToken) throw new CdkdError(`AssumeRole(${displayIdent(roleArn, { maxCodePoints: 613 })}) returned no usable credentials.`, "LOCAL_INVOKE_ASSUMEROLE_NO_CREDS");
|
|
33021
32171
|
return {
|
|
33022
32172
|
accessKeyId: creds.AccessKeyId,
|
|
@@ -33137,141 +32287,6 @@ function pickReferencedLogicalId(intrinsic) {
|
|
|
33137
32287
|
}
|
|
33138
32288
|
}
|
|
33139
32289
|
|
|
33140
|
-
// src/cli/commands/local-invoke/inline-code.ts
|
|
33141
|
-
function resolveInlineCodeFilePath(dir, modulePath, fileExtension, handler) {
|
|
33142
|
-
const resolved = resolveAssemblyPath(dir, `${modulePath}${fileExtension}`);
|
|
33143
|
-
if (!resolved.contained) throw new Error(`Handler ${displayAssemblyPath(handler)} names a module path that ${renderAssemblyPathEscape(resolved, dir, "materialize it", "A Handler's module path names a file inside the function's own code directory; one that leaves it would write the inline Code.ZipFile body to an arbitrary path on this machine. Refusing to materialize it.")}`);
|
|
33144
|
-
return resolved.path;
|
|
33145
|
-
}
|
|
33146
|
-
function materializeInlineCode(handler, source, fileExtension) {
|
|
33147
|
-
const lastDot = handler.lastIndexOf(".");
|
|
33148
|
-
if (lastDot <= 0) throw new Error(`Handler '${handler}' is malformed: expected '<modulePath>.<exportName>'.`);
|
|
33149
|
-
const modulePath = handler.substring(0, lastDot);
|
|
33150
|
-
const dir = mkdtempSync(path.join(tmpdir(), "cdkd-local-invoke-"));
|
|
33151
|
-
try {
|
|
33152
|
-
const filePath = resolveInlineCodeFilePath(dir, modulePath, fileExtension, handler);
|
|
33153
|
-
mkdirSync(path.dirname(filePath), { recursive: true });
|
|
33154
|
-
writeFileSync(filePath, source, "utf-8");
|
|
33155
|
-
} catch (e) {
|
|
33156
|
-
try {
|
|
33157
|
-
rmSync(dir, {
|
|
33158
|
-
recursive: true,
|
|
33159
|
-
force: true
|
|
33160
|
-
});
|
|
33161
|
-
} catch {}
|
|
33162
|
-
throw e;
|
|
33163
|
-
}
|
|
33164
|
-
return dir;
|
|
33165
|
-
}
|
|
33166
|
-
|
|
33167
|
-
// src/cli/commands/local-invoke/image-plan.ts
|
|
33168
|
-
async function resolveZipImagePlan(lambda, options) {
|
|
33169
|
-
let inlineTmpDir;
|
|
33170
|
-
let codeDir = lambda.codePath;
|
|
33171
|
-
if (codeDir === null) {
|
|
33172
|
-
inlineTmpDir = materializeInlineCode(lambda.handler, lambda.inlineCode ?? "", resolveRuntimeFileExtension(lambda.runtime));
|
|
33173
|
-
codeDir = inlineTmpDir;
|
|
33174
|
-
}
|
|
33175
|
-
const image = resolveRuntimeImage(lambda.runtime);
|
|
33176
|
-
await pullImage(image, options.pull === false);
|
|
33177
|
-
const layerPlan = await materializeLambdaLayersIncludingArns(lambda.layers, options, {
|
|
33178
|
-
logicalId: lambda.logicalId,
|
|
33179
|
-
cdkPath: readCdkPathOrUndefined(lambda.resource)
|
|
33180
|
-
});
|
|
33181
|
-
const containerCodePath = resolveRuntimeCodeMountPath(lambda.runtime);
|
|
33182
|
-
const tmpfs = resolveTmpfsForLambda(lambda);
|
|
33183
|
-
return {
|
|
33184
|
-
image,
|
|
33185
|
-
mounts: [{
|
|
33186
|
-
hostPath: codeDir,
|
|
33187
|
-
containerPath: containerCodePath,
|
|
33188
|
-
readOnly: true
|
|
33189
|
-
}],
|
|
33190
|
-
extraMounts: layerPlan.mount ? [layerPlan.mount] : [],
|
|
33191
|
-
cmd: [lambda.handler],
|
|
33192
|
-
platform: architectureToPlatform(lambda.architecture),
|
|
33193
|
-
...inlineTmpDir !== void 0 && { inlineTmpDir },
|
|
33194
|
-
...layerPlan.tmpDir !== void 0 && { layersTmpDir: layerPlan.tmpDir },
|
|
33195
|
-
...layerPlan.extraTmpDirs.length > 0 && { layerArnTmpDirs: layerPlan.extraTmpDirs },
|
|
33196
|
-
...tmpfs !== void 0 && { tmpfs }
|
|
33197
|
-
};
|
|
33198
|
-
}
|
|
33199
|
-
async function materializeLambdaLayersIncludingArns(layers, options, workload) {
|
|
33200
|
-
const extraTmpDirs = [];
|
|
33201
|
-
const flat = [];
|
|
33202
|
-
for (const layer of layers) {
|
|
33203
|
-
if (layer.kind === "asset") {
|
|
33204
|
-
flat.push({
|
|
33205
|
-
logicalId: layer.logicalId,
|
|
33206
|
-
assetPath: layer.assetPath
|
|
33207
|
-
});
|
|
33208
|
-
continue;
|
|
33209
|
-
}
|
|
33210
|
-
const dir = await materializeLayerFromArn(layer, {
|
|
33211
|
-
...workload && { workload },
|
|
33212
|
-
...options.layerRoleArn !== void 0 && { roleArn: explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn) }
|
|
33213
|
-
});
|
|
33214
|
-
extraTmpDirs.push(dir);
|
|
33215
|
-
flat.push({
|
|
33216
|
-
logicalId: layer.arn,
|
|
33217
|
-
assetPath: dir
|
|
33218
|
-
});
|
|
33219
|
-
}
|
|
33220
|
-
return {
|
|
33221
|
-
...materializeLambdaLayers(flat),
|
|
33222
|
-
extraTmpDirs
|
|
33223
|
-
};
|
|
33224
|
-
}
|
|
33225
|
-
function resolveTmpfsForLambda(lambda) {
|
|
33226
|
-
if (lambda.ephemeralStorageMb === void 0) return void 0;
|
|
33227
|
-
const logger = getLogger();
|
|
33228
|
-
if (lambda.kind === "image") logger.info(`Lambda ${lambda.logicalId}: capping /tmp at ${lambda.ephemeralStorageMb} MiB via --tmpfs (overlays any base-image /tmp content)`);
|
|
33229
|
-
else logger.debug(`Lambda ${lambda.logicalId}: applying EphemeralStorage cap via --tmpfs /tmp:size=${lambda.ephemeralStorageMb}m`);
|
|
33230
|
-
return {
|
|
33231
|
-
target: "/tmp",
|
|
33232
|
-
sizeMb: lambda.ephemeralStorageMb
|
|
33233
|
-
};
|
|
33234
|
-
}
|
|
33235
|
-
function materializeLambdaLayers(layers) {
|
|
33236
|
-
if (layers.length === 0) return {};
|
|
33237
|
-
if (layers.length === 1) return { mount: {
|
|
33238
|
-
hostPath: layers[0].assetPath,
|
|
33239
|
-
containerPath: "/opt",
|
|
33240
|
-
readOnly: true
|
|
33241
|
-
} };
|
|
33242
|
-
const tmpDir = mkdtempSync(path.join(tmpdir(), "cdkd-local-invoke-layers-"));
|
|
33243
|
-
try {
|
|
33244
|
-
for (const layer of layers) copyLayerTreeLastWins(layer.assetPath, tmpDir);
|
|
33245
|
-
} catch (error) {
|
|
33246
|
-
rmSync(tmpDir, {
|
|
33247
|
-
recursive: true,
|
|
33248
|
-
force: true
|
|
33249
|
-
});
|
|
33250
|
-
throw error;
|
|
33251
|
-
}
|
|
33252
|
-
return {
|
|
33253
|
-
mount: {
|
|
33254
|
-
hostPath: tmpDir,
|
|
33255
|
-
containerPath: "/opt",
|
|
33256
|
-
readOnly: true
|
|
33257
|
-
},
|
|
33258
|
-
tmpDir
|
|
33259
|
-
};
|
|
33260
|
-
}
|
|
33261
|
-
async function resolveLocalBuildPlan(lambda) {
|
|
33262
|
-
if (!lambda.stack.assetManifestPath) return void 0;
|
|
33263
|
-
const { manifestDir: cdkOutDir, assetOutdir } = assetPathDirs(lambda.stack);
|
|
33264
|
-
const manifest = await new AssetManifestLoader().loadStackManifest(lambda.stack, cdkOutDir);
|
|
33265
|
-
if (!manifest) return void 0;
|
|
33266
|
-
const entry = getDockerImageBySourceHash(manifest, lambda.imageUri);
|
|
33267
|
-
if (!entry) return void 0;
|
|
33268
|
-
return {
|
|
33269
|
-
asset: entry.asset,
|
|
33270
|
-
cdkOutDir,
|
|
33271
|
-
assetOutdir
|
|
33272
|
-
};
|
|
33273
|
-
}
|
|
33274
|
-
|
|
33275
32290
|
// src/cli/commands/local-invoke/template-env.ts
|
|
33276
32291
|
function envHasIntrinsicValue(templateEnv) {
|
|
33277
32292
|
if (!templateEnv) return false;
|
|
@@ -33429,6 +32444,10 @@ async function localInvokeCommand(target, options) {
|
|
|
33429
32444
|
if (typeof options.assumeRole === "string") explicitRoleArnOrThrow("--assume-role", options.assumeRole);
|
|
33430
32445
|
if (options.layerRoleArn !== void 0) explicitRoleArnOrThrow("--layer-role-arn", options.layerRoleArn);
|
|
33431
32446
|
if (options.ecrRoleArn !== void 0) assertFlagRoleArn("--ecr-role-arn", options.ecrRoleArn);
|
|
32447
|
+
checkEmulateRoleVia(options.emulateRoleVia, {
|
|
32448
|
+
roleFlag: "--assume-role",
|
|
32449
|
+
roleRequested: options.assumeRole === true || typeof options.assumeRole === "string"
|
|
32450
|
+
});
|
|
33432
32451
|
await activateLocalAwsAndRoleArn(options);
|
|
33433
32452
|
await ensureDockerAvailable();
|
|
33434
32453
|
const profileCredentials = await profileCredentialsForWorkload(options.profile, resolveProfileCredentials);
|
|
@@ -33454,7 +32473,7 @@ async function localInvokeCommand(target, options) {
|
|
|
33454
32473
|
const targetLabel = lambda.kind === "zip" ? lambda.runtime : "container image";
|
|
33455
32474
|
logger.info(`Target: ${lambda.stack.stackName}/${lambda.logicalId} (${targetLabel})`);
|
|
33456
32475
|
imagePlan = await resolveImagePlan(lambda, options);
|
|
33457
|
-
const { env: templateEnvResolved, sensitiveEnvKeys, stateForRoleHint } = await resolveInvokeTemplateEnv(lambda, options);
|
|
32476
|
+
const { env: templateEnvResolved, sensitiveEnvKeys, stateForRoleHint, stateRegion } = await resolveInvokeTemplateEnv(lambda, options);
|
|
33458
32477
|
let resolvedAssumeRoleArn;
|
|
33459
32478
|
if (typeof options.assumeRole === "string") resolvedAssumeRoleArn = explicitRoleArnOrThrow("--assume-role", options.assumeRole);
|
|
33460
32479
|
else if (options.assumeRole === true) {
|
|
@@ -33473,8 +32492,11 @@ async function localInvokeCommand(target, options) {
|
|
|
33473
32492
|
};
|
|
33474
32493
|
await applyLambdaCredentialEnv(dockerEnv, {
|
|
33475
32494
|
...resolvedAssumeRoleArn && { assumeRoleArn: resolvedAssumeRoleArn },
|
|
32495
|
+
...options.emulateRoleVia !== void 0 && { emulateRoleVia: options.emulateRoleVia },
|
|
33476
32496
|
...options.region !== void 0 && { region: options.region },
|
|
33477
32497
|
...lambda.stack.region !== void 0 && { stackRegion: lambda.stack.region },
|
|
32498
|
+
...stateRegion !== void 0 && { stateRegion },
|
|
32499
|
+
...options.profile !== void 0 && { profile: options.profile },
|
|
33478
32500
|
...profileCredentials && { profileCredentials },
|
|
33479
32501
|
...profileCredsFile && { profileCredsFile }
|
|
33480
32502
|
});
|
|
@@ -33611,7 +32633,8 @@ async function resolveInvokeTemplateEnvWith(lambda, options, dynamicRefs) {
|
|
|
33611
32633
|
return {
|
|
33612
32634
|
env: dynamic.env,
|
|
33613
32635
|
sensitiveEnvKeys: /* @__PURE__ */ new Set([...stateAudit?.sensitiveKeys ?? [], ...dynamic.resolvedKeys]),
|
|
33614
|
-
...stateForRoleHint !== void 0 && { stateForRoleHint }
|
|
32636
|
+
...stateForRoleHint !== void 0 && { stateForRoleHint },
|
|
32637
|
+
...ownerRegion !== void 0 && { stateRegion: ownerRegion }
|
|
33615
32638
|
};
|
|
33616
32639
|
}
|
|
33617
32640
|
async function resolveImagePlan(lambda, options) {
|
|
@@ -33621,12 +32644,16 @@ async function resolveImagePlan(lambda, options) {
|
|
|
33621
32644
|
async function resolveContainerImagePlan(lambda, options) {
|
|
33622
32645
|
const logger = getLogger();
|
|
33623
32646
|
const platform = architectureToPlatform(lambda.architecture);
|
|
33624
|
-
const localBuild = await resolveLocalBuildPlan(lambda);
|
|
32647
|
+
const localBuild = await resolveLocalBuildPlan$1(lambda);
|
|
33625
32648
|
let imageRef;
|
|
33626
32649
|
if (localBuild) imageRef = await buildContainerImage$1(localBuild.asset, localBuild.cdkOutDir, {
|
|
33627
32650
|
assetOutdir: localBuild.assetOutdir,
|
|
33628
32651
|
architecture: lambda.architecture,
|
|
33629
|
-
noBuild: options.build === false
|
|
32652
|
+
noBuild: options.build === false,
|
|
32653
|
+
workload: {
|
|
32654
|
+
logicalId: lambda.logicalId,
|
|
32655
|
+
cdkPath: readCdkPathOrUndefined(lambda.resource)
|
|
32656
|
+
}
|
|
33630
32657
|
});
|
|
33631
32658
|
else {
|
|
33632
32659
|
if (!parseEcrUri(lambda.imageUri)) throw new Error(`Container Lambda '${lambda.logicalId}' has no matching asset in cdk.out, and Code.ImageUri '${lambda.imageUri}' is not an ECR URI cdkd can authenticate against. Re-synthesize the CDK app (so cdk.out includes the build context) or deploy the image to ECR first.`);
|
|
@@ -33702,7 +32729,7 @@ function createLocalCommand() {
|
|
|
33702
32729
|
setEmbedConfig(CDKD_EMBED_CONFIG);
|
|
33703
32730
|
setAwsEndpointOverrideSource(mixedModeEmulatorOverride);
|
|
33704
32731
|
const local = new Command("local").description("Local execution of Lambda functions (RIE) and ECS task definitions (Docker required)");
|
|
33705
|
-
const invoke = new Command("invoke").description("Run a Lambda function locally in a Docker container (RIE-backed). Target accepts a CDK display path (MyStack/MyApi/Handler) or stack-qualified logical ID (MyStack:MyApiHandler1234ABCD). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the Lambda to invoke").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for IMAGE local-build path; `docker build` does not pull base layers by default")).addOption(new Option("--no-build", "Skip docker build on the IMAGE local-build path (use the previously-built tag). Requires the deterministic tag to already be in the local registry; errors with an actionable message when missing. No-op for ZIP Lambdas and the IMAGE ECR-pull path. Compatible with --no-pull.")).addOption(new Option("--debug-port <port>", "Node --inspect-brk port (default: off)")).addOption(new Option("--container-host <host>", "Host to bind the RIE port to").default("127.0.0.1")).addOption(new Option("--assume-role [arn]", "Assume the Lambda's deployed execution role and forward STS-issued temp credentials to the container so the handler runs with the deployed function's narrow permissions (closes the \"developer admin / function narrow\" skew). Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) auto-resolves the function's execution role ARN from cdkd state (requires --from-state); (3) `--no-assume-role` explicitly opts out (forces dev creds even with --from-state). Off by default — when omitted, the developer's shell credentials are forwarded unchanged (SAM-compatible default). STS failures degrade to a warn + dev-creds fallback.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the deployed execution role: forward your ambient AWS credentials (or the --profile overlay) even when --from-state is set, and suppress the \"run with --assume-role\" hint. Distinct from omitting the flag, which still prints that hint.")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub in env vars with the deployed physical IDs / attributes. Off by default — keep PR 1 warn-and-drop semantics; turn on for stacks already deployed via cdkd deploy.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localInvokeCommand));
|
|
32732
|
+
const invoke = new Command("invoke").description("Run a Lambda function locally in a Docker container (RIE-backed). Target accepts a CDK display path (MyStack/MyApi/Handler) or stack-qualified logical ID (MyStack:MyApiHandler1234ABCD). Single-stack apps may omit the stack prefix.").argument("<target>", "CDK display path or stack-qualified logical ID of the Lambda to invoke").addOption(new Option("-e, --event <file>", "JSON event payload file (default: {})")).addOption(new Option("--event-stdin", "Read event JSON from stdin").default(false)).addOption(new Option("--env-vars <file>", "JSON env-var overrides (SAM-compatible: {\"LogicalId\":{\"KEY\":\"VALUE\"}})")).addOption(new Option("--no-pull", "Skip docker pull (use cached image) — no-op for IMAGE local-build path; `docker build` does not pull base layers by default")).addOption(new Option("--no-build", "Skip docker build on the IMAGE local-build path (use the previously-built tag). Requires the deterministic tag to already be in the local registry; errors with an actionable message when missing. No-op for ZIP Lambdas and the IMAGE ECR-pull path. Compatible with --no-pull.")).addOption(new Option("--debug-port <port>", "Node --inspect-brk port (default: off)")).addOption(new Option("--container-host <host>", "Host to bind the RIE port to").default("127.0.0.1")).addOption(new Option("--assume-role [arn]", "Assume the Lambda's deployed execution role and forward STS-issued temp credentials to the container so the handler runs with the deployed function's narrow permissions (closes the \"developer admin / function narrow\" skew). Three forms: (1) `--assume-role <arn>` assumes the explicit ARN; (2) `--assume-role` (bare) auto-resolves the function's execution role ARN from cdkd state (requires --from-state); (3) `--no-assume-role` explicitly opts out (forces dev creds even with --from-state). Off by default — when omitted, the developer's shell credentials are forwarded unchanged (SAM-compatible default). STS failures degrade to a warn + dev-creds fallback.")).addOption(new Option("--no-assume-role", "Explicitly opt out of assuming the deployed execution role: forward your ambient AWS credentials (or the --profile overlay) even when --from-state is set, and suppress the \"run with --assume-role\" hint. Distinct from omitting the flag, which still prints that hint.")).addOption(emulateRoleViaOption("--assume-role")).addOption(new Option("--layer-role-arn <arn>", "Role to sts:AssumeRole before calling lambda:GetLayerVersion on every literal-ARN entry in Properties.Layers. Use only when the dev credentials cannot read the layer — typically cross-account layers. AWS-published public layers (e.g. Lambda Powertools) are readable from every account and need no role.")).addOption(new Option("--ecr-role-arn <arn>", "Role ARN to assume before authenticating against ECR for cross-account / centralized registries. Issues sts:AssumeRole via the default credential chain and uses the temporary credentials for ecr:GetAuthorizationToken + docker pull. Required when the caller does not have direct cross-account access to the target repository. A same-account pull in ANY region does not need this flag: the ECR client is built for the image URI's own region, so crossing a region costs nothing extra.")).addOption(new Option("--from-state", "Read cdkd S3 state for the target stack and substitute Ref / Fn::GetAtt / Fn::Sub in env vars with the deployed physical IDs / attributes. Off by default — keep PR 1 warn-and-drop semantics; turn on for stacks already deployed via cdkd deploy.").default(false)).addOption(new Option("--from-cfn-stack [cfn-stack-name]", "Read a deployed CloudFormation stack via ListStackResources and substitute Ref / Fn::ImportValue in env vars with the deployed physical IDs / exports. Use for CDK apps deployed via the upstream CDK CLI (`cdk deploy`). Bare form uses the cdkd stack name; pass an explicit value when CFn stack name differs. Mutually exclusive with --from-state. Fn::GetAtt is warn-and-dropped in v1 (CFn ListStackResources does not return per-attribute values).")).addOption(new Option("--stack-region <region>", "Region of the state record to read. Used with --from-state when the same stack name has state in multiple regions, and with --from-cfn-stack as the CFn client region (cdkd does not have a separate --cfn-stack-region flag).").argParser(parseStackRegion)).action(withErrorHandling(localInvokeCommand));
|
|
33706
32733
|
[
|
|
33707
32734
|
...commonOptions,
|
|
33708
32735
|
...appOptions,
|
|
@@ -33753,6 +32780,7 @@ function buildProgram() {
|
|
|
33753
32780
|
} catch (err) {
|
|
33754
32781
|
handleError(err);
|
|
33755
32782
|
}
|
|
32783
|
+
setLocalCustomResourceRuntimeEnabled(actionCommand.optsWithGlobals().localCustomResources !== false, actionCommand.parent?.parent ? `${actionCommand.parent.name()} ${actionCommand.name()}` : actionCommand.name());
|
|
33756
32784
|
await resolveS3ClientDefaults({ profile });
|
|
33757
32785
|
});
|
|
33758
32786
|
program.addCommand(createBootstrapCommand());
|
|
@@ -33793,4 +32821,4 @@ function collectVerbFlags(program) {
|
|
|
33793
32821
|
}
|
|
33794
32822
|
|
|
33795
32823
|
export { resolveSecretDerivedPrincipals as a, buildProgram, isResolvableSecretPrincipalList as i, runDestroyForStack as n, canonicalizeIpProtocolValue as o, holdsUnprovenSecretPrincipalToken as r, canonicalizeIpv4Cidr as t };
|
|
33796
|
-
//# sourceMappingURL=program-
|
|
32824
|
+
//# sourceMappingURL=program-BBGm88gl.js.map
|