@anthusai/papyrus 5.111.0 → 5.112.0-next.2
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/amplify/auth/resource.js +3 -0
- package/amplify/auth/resource.ts +3 -0
- package/amplify/auth/tenant-session-claims.js +27 -0
- package/amplify/auth/tenant-session-claims.ts +31 -0
- package/amplify/cost-attribution.js +12 -0
- package/amplify/cost-attribution.ts +12 -0
- package/amplify/data/resource.js +16 -0
- package/amplify/data/resource.ts +17 -0
- package/amplify/data/schema.js +20 -1
- package/amplify/data/schema.ts +21 -1
- package/amplify/functions/assignment-action/handler.ts +14 -9
- package/amplify/functions/automation-view/wire.js +2 -1
- package/amplify/functions/automation-view/wire.ts +2 -1
- package/amplify/functions/category-action/handler.ts +24 -18
- package/amplify/functions/category-action/message-hashtags.js +2 -1
- package/amplify/functions/category-action/message-hashtags.ts +2 -1
- package/amplify/functions/category-action/reference-links.js +3 -2
- package/amplify/functions/category-action/reference-links.ts +3 -2
- package/amplify/functions/console-chat-responder/resource.js +2 -1
- package/amplify/functions/console-chat-responder/resource.ts +2 -1
- package/amplify/functions/content-actions/handler.py +49 -21
- package/amplify/functions/content-actions/resource.js +4 -0
- package/amplify/functions/content-actions/resource.ts +5 -0
- package/amplify/functions/editorial-checks/handler.py +5 -1
- package/amplify/functions/editorial-checks/wire.js +2 -1
- package/amplify/functions/editorial-checks/wire.ts +2 -1
- package/amplify/functions/image-service/wire.js +2 -1
- package/amplify/functions/image-service/wire.ts +2 -1
- package/amplify/functions/monitoring-view/wire.js +2 -1
- package/amplify/functions/monitoring-view/wire.ts +2 -1
- package/amplify/functions/newsroom-summary/handler.ts +16 -12
- package/amplify/functions/shared/tenant-context.js +98 -0
- package/amplify/functions/shared/tenant-context.ts +33 -0
- package/amplify/functions/shared/tenant-scoped-client.ts +80 -0
- package/amplify/functions/tenant-claims/claims.ts +90 -0
- package/amplify/functions/tenant-claims/environment.js +7 -0
- package/amplify/functions/tenant-claims/environment.ts +7 -0
- package/amplify/functions/tenant-claims/handler.ts +56 -0
- package/amplify/functions/tenant-claims/resource.js +12 -0
- package/amplify/functions/tenant-claims/resource.ts +13 -0
- package/amplify/plugins/newsletter/sending.js +2 -1
- package/amplify/plugins/newsletter/sending.ts +2 -1
- package/amplify/plugins/notifications/papyrus.plugin.js +2 -1
- package/amplify/plugins/notifications/papyrus.plugin.ts +2 -1
- package/amplify/plugins/signup/papyrus.plugin.js +2 -1
- package/amplify/plugins/signup/papyrus.plugin.ts +2 -1
- package/amplify/shared-stack/alarms.js +53 -0
- package/amplify/shared-stack/alarms.ts +109 -0
- package/amplify/shared-stack/define.js +15 -0
- package/amplify/shared-stack/define.ts +17 -0
- package/amplify/shared-stack/deny.js +27 -0
- package/amplify/shared-stack/deny.ts +28 -0
- package/amplify/shared-stack/inline-policy.js +53 -0
- package/amplify/shared-stack/inline-policy.ts +65 -0
- package/amplify/shared-stack/isolation.js +161 -0
- package/amplify/shared-stack/isolation.ts +204 -0
- package/amplify/shared-stack/names.js +95 -0
- package/amplify/shared-stack/names.ts +133 -0
- package/amplify/shared-stack/settings.js +70 -0
- package/amplify/shared-stack/settings.ts +95 -0
- package/amplify/site-api-access.js +13 -0
- package/amplify/site-api-access.ts +14 -0
- package/amplify/site-backend-config.js +7 -1
- package/amplify/site-backend-config.ts +8 -2
- package/amplify/site-backend.js +65 -13
- package/amplify/site-backend.ts +75 -19
- package/components/news-desk-taxonomy-client.ts +5 -0
- package/components/newsroom-article-editor.tsx +7 -3
- package/components/newsroom-board-view.tsx +4 -2
- package/components/newsroom-organizer.css +2 -2
- package/components/use-newsroom-desk-sections.ts +31 -0
- package/infra/amplify-app-shell.js +4 -1
- package/infra/amplify-app-shell.ts +4 -1
- package/infra/build-specs.js +4 -1
- package/infra/build-specs.ts +5 -1
- package/infra/cost-tags.test.js +1 -1
- package/infra/cost-tags.test.ts +1 -1
- package/infra/shared-stack-deny.js +80 -0
- package/infra/shared-stack-deny.test.js +56 -0
- package/infra/shared-stack-deny.test.ts +66 -0
- package/infra/shared-stack-deny.ts +86 -0
- package/lib/newsroom-sections.ts +14 -0
- package/lib/tenant-keys.js +16 -0
- package/lib/tenant-keys.ts +19 -0
- package/package.json +2 -1
- package/routes.manifest.json +1 -1
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { Duration, type Stack } from "aws-cdk-lib";
|
|
2
|
+
import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
|
|
3
|
+
import { shortHash } from "./isolation";
|
|
4
|
+
import type { SharedTierPlan } from "./names";
|
|
5
|
+
import type { SharedStackSettings } from "./settings";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Layer 5 of the isolation: alarms that belong to one shared stack, separate from any dedicated site's. They carry no action:
|
|
9
|
+
* every CloudWatch alarm in the account reaches the operator through the default-bus listener (docs/operator-alerts.md), and
|
|
10
|
+
* the alarm names start with the stack's prefix so the operator sees which tier it is.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type SharedFunctionAlarmTarget = {
|
|
14
|
+
/** The function's own name, which `applySharedStackIsolation` set, so no cross-stack reference is needed. */
|
|
15
|
+
functionName: string;
|
|
16
|
+
/** Reserved concurrency; undefined for a function with none (an infrastructure function), which gets no concurrency alarm. */
|
|
17
|
+
reserved?: number;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type SharedAlarmInputs = {
|
|
21
|
+
functions: SharedFunctionAlarmTarget[];
|
|
22
|
+
appSyncApiId: string;
|
|
23
|
+
tableNames: string[];
|
|
24
|
+
/** The projection dead-letter queue's name, when the stack has a publication. */
|
|
25
|
+
projectionDeadLetterQueueName?: string;
|
|
26
|
+
/** The shared distribution's id, once one exists (PPY-3bbbf9); until then there is no purge to count. */
|
|
27
|
+
distributionId?: string;
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export const DYNAMODB_TABLES_PER_ALARM = 5;
|
|
31
|
+
|
|
32
|
+
const minutes = (settings: SharedStackSettings) => Duration.minutes(settings.alarms.periodMinutes);
|
|
33
|
+
|
|
34
|
+
function metricAlarm(scope: Stack, plan: SharedTierPlan, kind: string, key: string, metric: cloudwatch.IMetric, threshold: number, description: string, operator = cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) {
|
|
35
|
+
return new cloudwatch.Alarm(scope, `${kind}${shortHash(key, 8)}`, {
|
|
36
|
+
alarmName: `${plan.stackPrefix}-${kind}-${key.replace(new RegExp(`^${plan.stackPrefix}-`), "").slice(0, 60)}`.slice(0, 255),
|
|
37
|
+
alarmDescription: description,
|
|
38
|
+
metric,
|
|
39
|
+
threshold,
|
|
40
|
+
evaluationPeriods: 1,
|
|
41
|
+
comparisonOperator: operator,
|
|
42
|
+
treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function addSharedStackAlarms(scope: Stack, plan: SharedTierPlan, settings: SharedStackSettings, inputs: SharedAlarmInputs): cloudwatch.Alarm[] {
|
|
47
|
+
const period = minutes(settings);
|
|
48
|
+
const alarms: cloudwatch.Alarm[] = [];
|
|
49
|
+
const where = `the ${plan.tier} shared stack`;
|
|
50
|
+
|
|
51
|
+
for (const target of inputs.functions) {
|
|
52
|
+
const dimensionsMap = { FunctionName: target.functionName };
|
|
53
|
+
const lambdaMetric = (metricName: string, statistic: string) => new cloudwatch.Metric({ namespace: "AWS/Lambda", metricName, dimensionsMap, statistic, period });
|
|
54
|
+
alarms.push(
|
|
55
|
+
metricAlarm(scope, plan, "errors", target.functionName, lambdaMetric("Errors", "Sum"), settings.alarms.functionErrors,
|
|
56
|
+
`${target.functionName} in ${where} returned errors.`),
|
|
57
|
+
metricAlarm(scope, plan, "throttles", target.functionName, lambdaMetric("Throttles", "Sum"), settings.alarms.functionThrottles,
|
|
58
|
+
`${target.functionName} in ${where} was throttled: it reached its reserved concurrency.`),
|
|
59
|
+
);
|
|
60
|
+
if (target.reserved !== undefined) {
|
|
61
|
+
// Concurrency against the reserved share: the reservation is also this function's ceiling, so a share of it is the early warning.
|
|
62
|
+
const threshold = Math.max(1, Math.ceil(target.reserved * settings.alarms.concurrencyShareOfReserved));
|
|
63
|
+
alarms.push(
|
|
64
|
+
metricAlarm(scope, plan, "concurrency", target.functionName, lambdaMetric("ConcurrentExecutions", "Maximum"), threshold,
|
|
65
|
+
`${target.functionName} in ${where} reached ${settings.alarms.concurrencyShareOfReserved * 100}% of its reserved concurrency of ${target.reserved}.`),
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const appSync = (metricName: string) => new cloudwatch.Metric({ namespace: "AWS/AppSync", metricName, dimensionsMap: { GraphQLAPIId: inputs.appSyncApiId }, statistic: "Sum", period });
|
|
71
|
+
alarms.push(
|
|
72
|
+
metricAlarm(scope, plan, "appsync-5xx", "api", appSync("5XXError"), settings.alarms.appSyncServerErrors, `The AppSync API of ${where} returned server errors.`),
|
|
73
|
+
// AppSync has no throttle metric: a throttled request is answered 429 and counted in 4XXError.
|
|
74
|
+
metricAlarm(scope, plan, "appsync-4xx", "api", appSync("4XXError"), settings.alarms.appSyncClientErrors, `The AppSync API of ${where} returned many client errors; throttled requests (429) are counted here.`),
|
|
75
|
+
);
|
|
76
|
+
|
|
77
|
+
for (let index = 0; index < inputs.tableNames.length; index += DYNAMODB_TABLES_PER_ALARM) {
|
|
78
|
+
const chunk = inputs.tableNames.slice(index, index + DYNAMODB_TABLES_PER_ALARM);
|
|
79
|
+
const usingMetrics: Record<string, cloudwatch.IMetric> = {};
|
|
80
|
+
chunk.forEach((tableName, position) => {
|
|
81
|
+
for (const metricName of ["ReadThrottleEvents", "WriteThrottleEvents"]) {
|
|
82
|
+
usingMetrics[`m${position}${metricName[0].toLowerCase()}`] = new cloudwatch.Metric({ namespace: "AWS/DynamoDB", metricName, dimensionsMap: { TableName: tableName }, statistic: "Sum", period });
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
const group = `group-${index / DYNAMODB_TABLES_PER_ALARM + 1}`;
|
|
86
|
+
alarms.push(metricAlarm(
|
|
87
|
+
scope, plan, "dynamodb-throttles", group,
|
|
88
|
+
new cloudwatch.MathExpression({ expression: "SUM(METRICS())", usingMetrics, period, label: "Throttled reads and writes" }),
|
|
89
|
+
settings.alarms.dynamoDbThrottledRequests, `DynamoDB throttled reads or writes on ${chunk.length} tables of ${where}.`,
|
|
90
|
+
));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
if (inputs.projectionDeadLetterQueueName !== undefined) {
|
|
94
|
+
alarms.push(
|
|
95
|
+
metricAlarm(scope, plan, "projection-dlq", "queue",
|
|
96
|
+
new cloudwatch.Metric({ namespace: "AWS/SQS", metricName: "ApproximateNumberOfMessagesVisible", dimensionsMap: { QueueName: inputs.projectionDeadLetterQueueName }, statistic: "Maximum", period }),
|
|
97
|
+
settings.alarms.projectionDeadLetterMessages, `Failed projections are waiting in the dead-letter queue of ${where}.`),
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
if (inputs.distributionId !== undefined) {
|
|
102
|
+
alarms.push(
|
|
103
|
+
metricAlarm(scope, plan, "purged-paths", inputs.distributionId,
|
|
104
|
+
new cloudwatch.Metric({ namespace: "Papyrus/Edge", metricName: "InvalidatedPaths", dimensionsMap: { DistributionId: inputs.distributionId }, statistic: "Sum", period: Duration.days(7) }),
|
|
105
|
+
settings.alarms.purgedPathsPerWeek, `The shared distribution of ${where} purged many paths in a week (billable past the free allowance).`),
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
return alarms;
|
|
109
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { sharedTierPlan } from "./names.js";
|
|
2
|
+
/**
|
|
3
|
+
* The backend configuration of a shared stack: tenancy mode shared on the tier, a projection publication with no site's
|
|
4
|
+
* files, and none of the features that belong to one site's mailbox, chat workspace or backups. Nothing else is configured;
|
|
5
|
+
* a tenant's own settings live in the site store (PPY-ee1e02), never in this file.
|
|
6
|
+
*/
|
|
7
|
+
export function sharedStackBackendConfig(tier) {
|
|
8
|
+
return {
|
|
9
|
+
brandId: sharedTierPlan(tier).stackPrefix,
|
|
10
|
+
productionAppId: "",
|
|
11
|
+
tenancy: { mode: "shared", tier },
|
|
12
|
+
publication: { kind: "s3-projection", reprojectOnDeploy: false },
|
|
13
|
+
features: { inboundEmail: false, slack: false, storageBackups: false, cliRemoteLogin: false, cliOnFederationClient: false },
|
|
14
|
+
};
|
|
15
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { PapyrusSiteBackendConfig } from "../site-backend-config";
|
|
2
|
+
import { sharedTierPlan, type SharedTier } from "./names";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The backend configuration of a shared stack: tenancy mode shared on the tier, a projection publication with no site's
|
|
6
|
+
* files, and none of the features that belong to one site's mailbox, chat workspace or backups. Nothing else is configured;
|
|
7
|
+
* a tenant's own settings live in the site store (PPY-ee1e02), never in this file.
|
|
8
|
+
*/
|
|
9
|
+
export function sharedStackBackendConfig(tier: SharedTier): PapyrusSiteBackendConfig {
|
|
10
|
+
return {
|
|
11
|
+
brandId: sharedTierPlan(tier).stackPrefix,
|
|
12
|
+
productionAppId: "",
|
|
13
|
+
tenancy: { mode: "shared", tier },
|
|
14
|
+
publication: { kind: "s3-projection", reprojectOnDeploy: false },
|
|
15
|
+
features: { inboundEmail: false, slack: false, storageBackups: false, cliRemoteLogin: false, cliOnFederationClient: false },
|
|
16
|
+
};
|
|
17
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { Stack } from "aws-cdk-lib";
|
|
2
|
+
import { CfnRole } from "aws-cdk-lib/aws-iam";
|
|
3
|
+
import { appendInlinePolicy, appendInlinePolicyToRawRole, findAllOfType, findResourcesOfCfnType } from "./inline-policy.js";
|
|
4
|
+
import { SHARED_DENY_POLICY_NAME, sharedStackDenyPolicyDocument } from "./names.js";
|
|
5
|
+
/**
|
|
6
|
+
* The deny that closes the reverse direction of the isolation (docs/plans/multi-tenant-architecture.md, layer 3): a dedicated
|
|
7
|
+
* site's roles may not touch anything of the shared tier. Added as an inline policy, so no template gains a resource.
|
|
8
|
+
*
|
|
9
|
+
* `skip` names the stacks left alone. A dedicated backend with many models would pass CloudFormation's 2,500-resource limit
|
|
10
|
+
* if one change touched every per-model nested stack (Papyrus 5.99.0 rolled back that way, amplify/cost-tag-waves.ts), and a
|
|
11
|
+
* per-model data stack's roles can reach only their own table. Returns the number of roles that got the deny.
|
|
12
|
+
*/
|
|
13
|
+
export function addSharedStackDeny(scope, skip = () => false) {
|
|
14
|
+
const document = sharedStackDenyPolicyDocument();
|
|
15
|
+
const roles = findAllOfType(scope, CfnRole).filter((role) => !skip(Stack.of(role)));
|
|
16
|
+
for (const role of roles)
|
|
17
|
+
appendInlinePolicy(role, SHARED_DENY_POLICY_NAME, document);
|
|
18
|
+
// CDK writes the role of a custom resource provider as a raw resource, not a CfnRole.
|
|
19
|
+
const rawRoles = findResourcesOfCfnType(scope, "AWS::IAM::Role").filter((role) => !(role instanceof CfnRole) && !skip(Stack.of(role)));
|
|
20
|
+
for (const role of rawRoles)
|
|
21
|
+
appendInlinePolicyToRawRole(role, SHARED_DENY_POLICY_NAME, document);
|
|
22
|
+
return roles.length + rawRoles.length;
|
|
23
|
+
}
|
|
24
|
+
/** True for the nested stack of one data model (`data/PapyrusCmsApi/<Model>`), where the transformer puts the model's table role. */
|
|
25
|
+
export function isModelDataStack(stack, modelNames) {
|
|
26
|
+
return stack.node.scope?.node.id === "PapyrusCmsApi" && modelNames.has(stack.node.id);
|
|
27
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { Stack } from "aws-cdk-lib";
|
|
2
|
+
import { CfnRole } from "aws-cdk-lib/aws-iam";
|
|
3
|
+
import type { IConstruct } from "constructs";
|
|
4
|
+
import { appendInlinePolicy, appendInlinePolicyToRawRole, findAllOfType, findResourcesOfCfnType } from "./inline-policy";
|
|
5
|
+
import { SHARED_DENY_POLICY_NAME, sharedStackDenyPolicyDocument } from "./names";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The deny that closes the reverse direction of the isolation (docs/plans/multi-tenant-architecture.md, layer 3): a dedicated
|
|
9
|
+
* site's roles may not touch anything of the shared tier. Added as an inline policy, so no template gains a resource.
|
|
10
|
+
*
|
|
11
|
+
* `skip` names the stacks left alone. A dedicated backend with many models would pass CloudFormation's 2,500-resource limit
|
|
12
|
+
* if one change touched every per-model nested stack (Papyrus 5.99.0 rolled back that way, amplify/cost-tag-waves.ts), and a
|
|
13
|
+
* per-model data stack's roles can reach only their own table. Returns the number of roles that got the deny.
|
|
14
|
+
*/
|
|
15
|
+
export function addSharedStackDeny(scope: IConstruct, skip: (stack: Stack) => boolean = () => false): number {
|
|
16
|
+
const document = sharedStackDenyPolicyDocument();
|
|
17
|
+
const roles = findAllOfType(scope, CfnRole).filter((role) => !skip(Stack.of(role)));
|
|
18
|
+
for (const role of roles) appendInlinePolicy(role, SHARED_DENY_POLICY_NAME, document);
|
|
19
|
+
// CDK writes the role of a custom resource provider as a raw resource, not a CfnRole.
|
|
20
|
+
const rawRoles = findResourcesOfCfnType(scope, "AWS::IAM::Role").filter((role) => !(role instanceof CfnRole) && !skip(Stack.of(role)));
|
|
21
|
+
for (const role of rawRoles) appendInlinePolicyToRawRole(role, SHARED_DENY_POLICY_NAME, document);
|
|
22
|
+
return roles.length + rawRoles.length;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** True for the nested stack of one data model (`data/PapyrusCmsApi/<Model>`), where the transformer puts the model's table role. */
|
|
26
|
+
export function isModelDataStack(stack: Stack, modelNames: ReadonlySet<string>): boolean {
|
|
27
|
+
return stack.node.scope?.node.id === "PapyrusCmsApi" && modelNames.has(stack.node.id);
|
|
28
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { CfnResource, Lazy, Stack, Token } from "aws-cdk-lib";
|
|
2
|
+
/** Every L1 resource of a type under `scope`, in construct-tree order. */
|
|
3
|
+
export function findAllOfType(scope, type) {
|
|
4
|
+
return scope.node.findAll().filter((node) => node instanceof type);
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Adds one inline policy to a role without adding a resource: `Policies` gains an entry, so the template holds exactly the
|
|
8
|
+
* resources it held before. Refuses a role whose `Policies` is not a plain list (a token cannot be extended safely).
|
|
9
|
+
*/
|
|
10
|
+
export function appendInlinePolicy(role, policyName, policyDocument) {
|
|
11
|
+
const existing = role.policies;
|
|
12
|
+
if (existing !== undefined && (Token.isUnresolved(existing) || !Array.isArray(existing))) {
|
|
13
|
+
throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a plain list.`);
|
|
14
|
+
}
|
|
15
|
+
if (existing?.some((entry) => !Token.isUnresolved(entry) && entry.policyName === policyName)) {
|
|
16
|
+
throw new Error(`Role ${role.node.path} already has a ${policyName} policy.`);
|
|
17
|
+
}
|
|
18
|
+
role.policies = [...(existing ?? []), { policyName, policyDocument }];
|
|
19
|
+
}
|
|
20
|
+
/** Every resource of a CloudFormation type under `scope`, including the raw `CfnResource`s CDK writes for its own providers. */
|
|
21
|
+
export function findResourcesOfCfnType(scope, cfnType) {
|
|
22
|
+
return scope.node.findAll().filter((node) => CfnResource.isCfnResource(node) && node.cfnResourceType === cfnType);
|
|
23
|
+
}
|
|
24
|
+
/** Like `appendInlinePolicy`, for a raw `CfnResource` of type AWS::IAM::Role (a custom resource provider's role). */
|
|
25
|
+
export function appendInlinePolicyToRawRole(role, policyName, policyDocument) {
|
|
26
|
+
const previous = role.cfnProperties.Policies;
|
|
27
|
+
// A provider's own statements arrive lazily, so the list is read when the template is written.
|
|
28
|
+
role.addPropertyOverride("Policies", Lazy.any({
|
|
29
|
+
produce: () => {
|
|
30
|
+
const resolved = Stack.of(role).resolve(previous) ?? [];
|
|
31
|
+
if (!Array.isArray(resolved))
|
|
32
|
+
throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a list.`);
|
|
33
|
+
return [...resolved, { PolicyName: policyName, PolicyDocument: policyDocument }];
|
|
34
|
+
},
|
|
35
|
+
}));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The functions CDK and Amplify write for their own plumbing (custom resource providers, the branch linker, the secret fetcher, the
|
|
39
|
+
* table manager, log retention, bucket deployment). They run at deploy time only; every other function is a shared function that
|
|
40
|
+
* gets reserved concurrency.
|
|
41
|
+
*/
|
|
42
|
+
export const INFRASTRUCTURE_FUNCTION_ID = /^(AWS[0-9a-f]{32}|framework-.*|LogRetention.*|Custom.*|BucketNotificationsHandler.*|Provider.*|Amplify(BranchLinker|SecretFetcher).*|TableManager.*)$/;
|
|
43
|
+
/** The construct id that names a function's owner: the L2 `Function`'s id, a provider's id for the raw function it writes, else the resource's own id. */
|
|
44
|
+
export function functionOwnerId(fn) {
|
|
45
|
+
return fn.node.id === "Resource" || fn.node.id === "Handler" ? (fn.node.scope?.node.id ?? fn.node.id) : fn.node.id;
|
|
46
|
+
}
|
|
47
|
+
export function isInfrastructureFunction(fn) {
|
|
48
|
+
return INFRASTRUCTURE_FUNCTION_ID.test(functionOwnerId(fn));
|
|
49
|
+
}
|
|
50
|
+
/** True for the construct id of a function CDK or Amplify writes for its own plumbing (see INFRASTRUCTURE_FUNCTION_ID). */
|
|
51
|
+
export function isInfrastructureConstructId(id) {
|
|
52
|
+
return INFRASTRUCTURE_FUNCTION_ID.test(id);
|
|
53
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { CfnResource, Lazy, Stack, Token } from "aws-cdk-lib";
|
|
2
|
+
import { CfnRole } from "aws-cdk-lib/aws-iam";
|
|
3
|
+
import type { IConstruct } from "constructs";
|
|
4
|
+
|
|
5
|
+
/** Every L1 resource of a type under `scope`, in construct-tree order. */
|
|
6
|
+
export function findAllOfType<T extends IConstruct>(scope: IConstruct, type: abstract new (...args: never[]) => T): T[] {
|
|
7
|
+
return scope.node.findAll().filter((node): node is T => node instanceof type);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Adds one inline policy to a role without adding a resource: `Policies` gains an entry, so the template holds exactly the
|
|
12
|
+
* resources it held before. Refuses a role whose `Policies` is not a plain list (a token cannot be extended safely).
|
|
13
|
+
*/
|
|
14
|
+
export function appendInlinePolicy(role: CfnRole, policyName: string, policyDocument: object): void {
|
|
15
|
+
const existing = role.policies;
|
|
16
|
+
if (existing !== undefined && (Token.isUnresolved(existing) || !Array.isArray(existing))) {
|
|
17
|
+
throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a plain list.`);
|
|
18
|
+
}
|
|
19
|
+
if (existing?.some((entry) => !Token.isUnresolved(entry) && (entry as { policyName?: string }).policyName === policyName)) {
|
|
20
|
+
throw new Error(`Role ${role.node.path} already has a ${policyName} policy.`);
|
|
21
|
+
}
|
|
22
|
+
role.policies = [...(existing ?? []), { policyName, policyDocument }];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Every resource of a CloudFormation type under `scope`, including the raw `CfnResource`s CDK writes for its own providers. */
|
|
26
|
+
export function findResourcesOfCfnType(scope: IConstruct, cfnType: string): CfnResource[] {
|
|
27
|
+
return scope.node.findAll().filter((node): node is CfnResource => CfnResource.isCfnResource(node) && node.cfnResourceType === cfnType);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Like `appendInlinePolicy`, for a raw `CfnResource` of type AWS::IAM::Role (a custom resource provider's role). */
|
|
31
|
+
export function appendInlinePolicyToRawRole(role: CfnResource, policyName: string, policyDocument: object): void {
|
|
32
|
+
const previous = (role as unknown as { cfnProperties: Record<string, unknown> }).cfnProperties.Policies;
|
|
33
|
+
// A provider's own statements arrive lazily, so the list is read when the template is written.
|
|
34
|
+
role.addPropertyOverride(
|
|
35
|
+
"Policies",
|
|
36
|
+
Lazy.any({
|
|
37
|
+
produce: () => {
|
|
38
|
+
const resolved = Stack.of(role).resolve(previous) ?? [];
|
|
39
|
+
if (!Array.isArray(resolved)) throw new Error(`Cannot add the ${policyName} policy to role ${role.node.path}: its Policies is not a list.`);
|
|
40
|
+
return [...resolved, { PolicyName: policyName, PolicyDocument: policyDocument }];
|
|
41
|
+
},
|
|
42
|
+
}),
|
|
43
|
+
);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The functions CDK and Amplify write for their own plumbing (custom resource providers, the branch linker, the secret fetcher, the
|
|
48
|
+
* table manager, log retention, bucket deployment). They run at deploy time only; every other function is a shared function that
|
|
49
|
+
* gets reserved concurrency.
|
|
50
|
+
*/
|
|
51
|
+
export const INFRASTRUCTURE_FUNCTION_ID = /^(AWS[0-9a-f]{32}|framework-.*|LogRetention.*|Custom.*|BucketNotificationsHandler.*|Provider.*|Amplify(BranchLinker|SecretFetcher).*|TableManager.*)$/;
|
|
52
|
+
|
|
53
|
+
/** The construct id that names a function's owner: the L2 `Function`'s id, a provider's id for the raw function it writes, else the resource's own id. */
|
|
54
|
+
export function functionOwnerId(fn: CfnResource): string {
|
|
55
|
+
return fn.node.id === "Resource" || fn.node.id === "Handler" ? (fn.node.scope?.node.id ?? fn.node.id) : fn.node.id;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function isInfrastructureFunction(fn: CfnResource): boolean {
|
|
59
|
+
return INFRASTRUCTURE_FUNCTION_ID.test(functionOwnerId(fn));
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** True for the construct id of a function CDK or Amplify writes for its own plumbing (see INFRASTRUCTURE_FUNCTION_ID). */
|
|
63
|
+
export function isInfrastructureConstructId(id: string): boolean {
|
|
64
|
+
return INFRASTRUCTURE_FUNCTION_ID.test(id);
|
|
65
|
+
}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { Aws, CfnParameter, Fn, RemovalPolicy, Stack, Token } from "aws-cdk-lib";
|
|
2
|
+
import { CfnRole } from "aws-cdk-lib/aws-iam";
|
|
3
|
+
import { CfnLogGroup } from "aws-cdk-lib/aws-logs";
|
|
4
|
+
import { CfnBucket } from "aws-cdk-lib/aws-s3";
|
|
5
|
+
import { CfnIndex, CfnVectorBucket } from "aws-cdk-lib/aws-s3vectors";
|
|
6
|
+
import { CfnQueue } from "aws-cdk-lib/aws-sqs";
|
|
7
|
+
import { CfnTable } from "aws-cdk-lib/aws-dynamodb";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { appendInlinePolicy, appendInlinePolicyToRawRole, findAllOfType, findResourcesOfCfnType, functionOwnerId, isInfrastructureFunction } from "./inline-policy.js";
|
|
10
|
+
/** What the key could not be attached to, by resource type, because Amplify or the service gives no way to. */
|
|
11
|
+
export const RESOURCES_THAT_CANNOT_TAKE_THE_KEY = [
|
|
12
|
+
{
|
|
13
|
+
resource: "Amplify secrets (secret(\"GOOGLE_CLIENT_ID\") and the other secret() values)",
|
|
14
|
+
reason: "Amplify Gen 2 stores them in SSM under /amplify/<app id>/ with the AWS-managed key and has no hook to choose another key.",
|
|
15
|
+
},
|
|
16
|
+
{
|
|
17
|
+
resource: "SecureString parameters made by custom resources (plugins that write one, such as newsletter)",
|
|
18
|
+
reason: "the shared stack runs no plugin that does; a plugin that is turned on later must be given the key by its custom resource handler.",
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
resource: "CloudFront KeyValueStore of the projection publication",
|
|
22
|
+
reason: "CloudFront key value stores have no KMS option; the store holds redirects only, no tenant content.",
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
resource: "Cognito user pool",
|
|
26
|
+
reason: "Cognito encrypts with AWS-owned keys and offers no customer-managed key.",
|
|
27
|
+
},
|
|
28
|
+
{
|
|
29
|
+
resource: "AppSync API",
|
|
30
|
+
reason: "AppSync encrypts at rest with AWS-owned keys and offers no customer-managed key; the data lives in the tables and bucket, which take the key.",
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
resource: "Lambda environment variables and code",
|
|
34
|
+
reason: "the Amplify function constructs expose no KMS key for them; the variables hold names and settings, no secrets.",
|
|
35
|
+
},
|
|
36
|
+
];
|
|
37
|
+
export function shortHash(value, length = 8) {
|
|
38
|
+
return createHash("sha256").update(value).digest("hex").slice(0, length);
|
|
39
|
+
}
|
|
40
|
+
function slug(value, max) {
|
|
41
|
+
return value.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, max).replace(/-+$/g, "");
|
|
42
|
+
}
|
|
43
|
+
export function boundaryPolicyArn(plan) {
|
|
44
|
+
return `arn:${Aws.PARTITION}:iam::${Aws.ACCOUNT_ID}:policy/${plan.boundaryPolicyName}`;
|
|
45
|
+
}
|
|
46
|
+
/** The statement a shared role needs to use the stack's key; the boundary also allows it, the key policy admits the role path. */
|
|
47
|
+
export function keyUseStatement(keyArn) {
|
|
48
|
+
return {
|
|
49
|
+
Sid: "UseTheSharedStackKey",
|
|
50
|
+
Effect: "Allow",
|
|
51
|
+
Action: ["kms:Encrypt", "kms:Decrypt", "kms:ReEncrypt*", "kms:GenerateDataKey*", "kms:DescribeKey", "kms:CreateGrant"],
|
|
52
|
+
Resource: [keyArn],
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
export function applySharedStackIsolation(backend, plan, settings) {
|
|
56
|
+
const root = backend.stack;
|
|
57
|
+
const keyParameter = new CfnParameter(root, "PapyrusSharedKmsKeyArn", {
|
|
58
|
+
type: "AWS::SSM::Parameter::Value<String>",
|
|
59
|
+
default: plan.keyArnParameter,
|
|
60
|
+
description: `The ${plan.tier} shared stack's KMS key ARN, written by the ${plan.foundationStackName} stack.`,
|
|
61
|
+
});
|
|
62
|
+
const keyArn = keyParameter.valueAsString;
|
|
63
|
+
const encryption = { sseEnabled: true, sseType: "KMS", kmsMasterKeyId: keyArn };
|
|
64
|
+
// Amplify's model tables are made by a custom resource, so the key goes through the table wrapper.
|
|
65
|
+
const amplifyTables = Object.values(backend.data.resources.cfnResources.amplifyDynamoDbTables);
|
|
66
|
+
for (const table of amplifyTables)
|
|
67
|
+
table.sseSpecification = encryption;
|
|
68
|
+
const roles = findAllOfType(root, CfnRole);
|
|
69
|
+
const boundary = boundaryPolicyArn(plan);
|
|
70
|
+
const keyUsePolicy = { Version: "2012-10-17", Statement: [keyUseStatement(keyArn)] };
|
|
71
|
+
for (const role of roles) {
|
|
72
|
+
role.path = plan.rolePath;
|
|
73
|
+
role.permissionsBoundary = boundary;
|
|
74
|
+
appendInlinePolicy(role, `${plan.stackPrefix}-key-use`, keyUsePolicy);
|
|
75
|
+
}
|
|
76
|
+
// CDK writes the role of a custom resource provider as a raw resource, not a CfnRole.
|
|
77
|
+
const rawRoles = findResourcesOfCfnType(root, "AWS::IAM::Role").filter((role) => !(role instanceof CfnRole));
|
|
78
|
+
for (const role of rawRoles) {
|
|
79
|
+
role.addPropertyOverride("Path", plan.rolePath);
|
|
80
|
+
role.addPropertyOverride("PermissionsBoundary", boundary);
|
|
81
|
+
appendInlinePolicyToRawRole(role, `${plan.stackPrefix}-key-use`, keyUsePolicy);
|
|
82
|
+
}
|
|
83
|
+
let tables = amplifyTables.length;
|
|
84
|
+
for (const table of findAllOfType(root, CfnTable)) {
|
|
85
|
+
table.sseSpecification = { sseEnabled: true, sseType: "KMS", kmsMasterKeyId: keyArn };
|
|
86
|
+
tables += 1;
|
|
87
|
+
}
|
|
88
|
+
const buckets = findAllOfType(root, CfnBucket);
|
|
89
|
+
for (const bucket of buckets) {
|
|
90
|
+
// A bucket name that carries the stack's prefix lets the boundary and the dedicated deny match objects, which have no tags of their own.
|
|
91
|
+
const named = bucket.bucketName;
|
|
92
|
+
if (typeof named === "string" && !Token.isUnresolved(named)) {
|
|
93
|
+
if (!named.startsWith(`${plan.stackPrefix}-`))
|
|
94
|
+
throw new Error(`Bucket ${bucket.node.path} is named ${named}, which does not start with ${plan.stackPrefix}-.`);
|
|
95
|
+
}
|
|
96
|
+
else {
|
|
97
|
+
bucket.bucketName = Fn.join("-", [plan.stackPrefix, shortHash(bucket.node.path), Aws.ACCOUNT_ID, Aws.REGION]);
|
|
98
|
+
}
|
|
99
|
+
bucket.bucketEncryption = {
|
|
100
|
+
serverSideEncryptionConfiguration: [{ bucketKeyEnabled: true, serverSideEncryptionByDefault: { sseAlgorithm: "aws:kms", kmsMasterKeyId: keyArn } }],
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
const queues = findAllOfType(root, CfnQueue);
|
|
104
|
+
for (const queue of queues) {
|
|
105
|
+
// SQS-managed and KMS encryption exclude each other.
|
|
106
|
+
queue.sqsManagedSseEnabled = undefined;
|
|
107
|
+
queue.kmsMasterKeyId = keyArn;
|
|
108
|
+
}
|
|
109
|
+
let vectorResources = 0;
|
|
110
|
+
for (const vectorBucket of findAllOfType(root, CfnVectorBucket)) {
|
|
111
|
+
vectorBucket.encryptionConfiguration = { sseType: "aws:kms", kmsKeyArn: keyArn };
|
|
112
|
+
vectorResources += 1;
|
|
113
|
+
}
|
|
114
|
+
for (const index of findAllOfType(root, CfnIndex)) {
|
|
115
|
+
index.encryptionConfiguration = { sseType: "aws:kms", kmsKeyArn: keyArn };
|
|
116
|
+
vectorResources += 1;
|
|
117
|
+
}
|
|
118
|
+
const functions = findResourcesOfCfnType(root, "AWS::Lambda::Function");
|
|
119
|
+
const reservedFunctions = [];
|
|
120
|
+
const functionTargets = [];
|
|
121
|
+
let reservedTotal = 0;
|
|
122
|
+
let logGroups = 0;
|
|
123
|
+
for (const fn of functions) {
|
|
124
|
+
const owner = functionOwnerId(fn);
|
|
125
|
+
const name = `${plan.stackPrefix}-${slug(owner, 24)}-${shortHash(fn.node.path, 10)}`;
|
|
126
|
+
fn.addPropertyOverride("FunctionName", name);
|
|
127
|
+
const group = new CfnLogGroup(Stack.of(fn), `${owner}SharedLogGroup${shortHash(fn.node.path, 6)}`, {
|
|
128
|
+
logGroupName: `/aws/lambda/${name}`,
|
|
129
|
+
kmsKeyId: keyArn,
|
|
130
|
+
retentionInDays: settings.logRetentionDays,
|
|
131
|
+
});
|
|
132
|
+
group.applyRemovalPolicy(RemovalPolicy.RETAIN);
|
|
133
|
+
fn.addDependency(group);
|
|
134
|
+
logGroups += 1;
|
|
135
|
+
if (isInfrastructureFunction(fn)) {
|
|
136
|
+
functionTargets.push({ functionName: name });
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
const reserved = settings.reservedConcurrency.overrides[owner] ?? settings.reservedConcurrency.perFunction;
|
|
140
|
+
fn.addPropertyOverride("ReservedConcurrentExecutions", reserved);
|
|
141
|
+
reservedFunctions.push(owner);
|
|
142
|
+
functionTargets.push({ functionName: name, reserved });
|
|
143
|
+
reservedTotal += reserved;
|
|
144
|
+
}
|
|
145
|
+
if (reservedTotal > settings.reservedConcurrency.tierLimit) {
|
|
146
|
+
throw new Error(`The ${plan.tier} shared stack reserves ${reservedTotal} concurrent executions across ${reservedFunctions.length} functions, over its tierLimit of ${settings.reservedConcurrency.tierLimit} in amplify/shared-stack/settings.ts.`);
|
|
147
|
+
}
|
|
148
|
+
return {
|
|
149
|
+
keyArnParameter: plan.keyArnParameter,
|
|
150
|
+
roles: roles.length + rawRoles.length,
|
|
151
|
+
functions: functions.length,
|
|
152
|
+
reservedFunctions,
|
|
153
|
+
functionTargets,
|
|
154
|
+
reservedTotal,
|
|
155
|
+
buckets: buckets.length,
|
|
156
|
+
queues: queues.length,
|
|
157
|
+
tables,
|
|
158
|
+
logGroups,
|
|
159
|
+
vectorResources,
|
|
160
|
+
};
|
|
161
|
+
}
|