@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.
Files changed (86) hide show
  1. package/amplify/auth/resource.js +3 -0
  2. package/amplify/auth/resource.ts +3 -0
  3. package/amplify/auth/tenant-session-claims.js +27 -0
  4. package/amplify/auth/tenant-session-claims.ts +31 -0
  5. package/amplify/cost-attribution.js +12 -0
  6. package/amplify/cost-attribution.ts +12 -0
  7. package/amplify/data/resource.js +16 -0
  8. package/amplify/data/resource.ts +17 -0
  9. package/amplify/data/schema.js +20 -1
  10. package/amplify/data/schema.ts +21 -1
  11. package/amplify/functions/assignment-action/handler.ts +14 -9
  12. package/amplify/functions/automation-view/wire.js +2 -1
  13. package/amplify/functions/automation-view/wire.ts +2 -1
  14. package/amplify/functions/category-action/handler.ts +24 -18
  15. package/amplify/functions/category-action/message-hashtags.js +2 -1
  16. package/amplify/functions/category-action/message-hashtags.ts +2 -1
  17. package/amplify/functions/category-action/reference-links.js +3 -2
  18. package/amplify/functions/category-action/reference-links.ts +3 -2
  19. package/amplify/functions/console-chat-responder/resource.js +2 -1
  20. package/amplify/functions/console-chat-responder/resource.ts +2 -1
  21. package/amplify/functions/content-actions/handler.py +49 -21
  22. package/amplify/functions/content-actions/resource.js +4 -0
  23. package/amplify/functions/content-actions/resource.ts +5 -0
  24. package/amplify/functions/editorial-checks/handler.py +5 -1
  25. package/amplify/functions/editorial-checks/wire.js +2 -1
  26. package/amplify/functions/editorial-checks/wire.ts +2 -1
  27. package/amplify/functions/image-service/wire.js +2 -1
  28. package/amplify/functions/image-service/wire.ts +2 -1
  29. package/amplify/functions/monitoring-view/wire.js +2 -1
  30. package/amplify/functions/monitoring-view/wire.ts +2 -1
  31. package/amplify/functions/newsroom-summary/handler.ts +16 -12
  32. package/amplify/functions/shared/tenant-context.js +98 -0
  33. package/amplify/functions/shared/tenant-context.ts +33 -0
  34. package/amplify/functions/shared/tenant-scoped-client.ts +80 -0
  35. package/amplify/functions/tenant-claims/claims.ts +90 -0
  36. package/amplify/functions/tenant-claims/environment.js +7 -0
  37. package/amplify/functions/tenant-claims/environment.ts +7 -0
  38. package/amplify/functions/tenant-claims/handler.ts +56 -0
  39. package/amplify/functions/tenant-claims/resource.js +12 -0
  40. package/amplify/functions/tenant-claims/resource.ts +13 -0
  41. package/amplify/plugins/newsletter/sending.js +2 -1
  42. package/amplify/plugins/newsletter/sending.ts +2 -1
  43. package/amplify/plugins/notifications/papyrus.plugin.js +2 -1
  44. package/amplify/plugins/notifications/papyrus.plugin.ts +2 -1
  45. package/amplify/plugins/signup/papyrus.plugin.js +2 -1
  46. package/amplify/plugins/signup/papyrus.plugin.ts +2 -1
  47. package/amplify/shared-stack/alarms.js +53 -0
  48. package/amplify/shared-stack/alarms.ts +109 -0
  49. package/amplify/shared-stack/define.js +15 -0
  50. package/amplify/shared-stack/define.ts +17 -0
  51. package/amplify/shared-stack/deny.js +27 -0
  52. package/amplify/shared-stack/deny.ts +28 -0
  53. package/amplify/shared-stack/inline-policy.js +53 -0
  54. package/amplify/shared-stack/inline-policy.ts +65 -0
  55. package/amplify/shared-stack/isolation.js +161 -0
  56. package/amplify/shared-stack/isolation.ts +204 -0
  57. package/amplify/shared-stack/names.js +95 -0
  58. package/amplify/shared-stack/names.ts +133 -0
  59. package/amplify/shared-stack/settings.js +70 -0
  60. package/amplify/shared-stack/settings.ts +95 -0
  61. package/amplify/site-api-access.js +13 -0
  62. package/amplify/site-api-access.ts +14 -0
  63. package/amplify/site-backend-config.js +7 -1
  64. package/amplify/site-backend-config.ts +8 -2
  65. package/amplify/site-backend.js +65 -13
  66. package/amplify/site-backend.ts +75 -19
  67. package/components/news-desk-taxonomy-client.ts +5 -0
  68. package/components/newsroom-article-editor.tsx +7 -3
  69. package/components/newsroom-board-view.tsx +4 -2
  70. package/components/newsroom-organizer.css +2 -2
  71. package/components/use-newsroom-desk-sections.ts +31 -0
  72. package/infra/amplify-app-shell.js +4 -1
  73. package/infra/amplify-app-shell.ts +4 -1
  74. package/infra/build-specs.js +4 -1
  75. package/infra/build-specs.ts +5 -1
  76. package/infra/cost-tags.test.js +1 -1
  77. package/infra/cost-tags.test.ts +1 -1
  78. package/infra/shared-stack-deny.js +80 -0
  79. package/infra/shared-stack-deny.test.js +56 -0
  80. package/infra/shared-stack-deny.test.ts +66 -0
  81. package/infra/shared-stack-deny.ts +86 -0
  82. package/lib/newsroom-sections.ts +14 -0
  83. package/lib/tenant-keys.js +16 -0
  84. package/lib/tenant-keys.ts +19 -0
  85. package/package.json +2 -1
  86. package/routes.manifest.json +1 -1
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The tenant a function call acts for, built once from an AppSync resolver event's identity.
3
+ * A signed-in caller carries one tenant in its token claims (docs/plans/tenant-claims-spike-1.md); an IAM caller names it
4
+ * explicitly. A shared stack refuses a call that cannot name exactly one tenant; a dedicated stack acts for its fixed
5
+ * site tenant. The tenant never comes from the request body and is never guessed.
6
+ * Python twin: src/papyrus_content/tenant_context.py; both read features_backend/fixtures/tenant-context/vectors.json.
7
+ */
8
+ import { AsyncLocalStorage } from "node:async_hooks";
9
+ import { isSharedStack, tenantIdFromEnvironment, validateTenantId } from "../../../lib/tenant-keys.js";
10
+ export const ROLE_CLAIMS = [
11
+ ["admin", "papyrus_tenant_admin"],
12
+ ["editor", "papyrus_tenant_editor"],
13
+ ["curator", "papyrus_tenant_curator"],
14
+ ["member", "papyrus_tenant_member"],
15
+ ];
16
+ export class TenantContextRefusal extends Error {
17
+ reason;
18
+ constructor(reason, message) {
19
+ super(message);
20
+ this.reason = reason;
21
+ this.name = "TenantContextRefusal";
22
+ }
23
+ }
24
+ function checked(tenantId) {
25
+ if (typeof tenantId !== "string")
26
+ throw new TenantContextRefusal("invalid_tenant", "A tenant id must be a string.");
27
+ try {
28
+ return validateTenantId(tenantId);
29
+ }
30
+ catch (error) {
31
+ throw new TenantContextRefusal("invalid_tenant", error.message);
32
+ }
33
+ }
34
+ function claimed(claims) {
35
+ const named = ROLE_CLAIMS.filter(([, claim]) => claims[claim] !== undefined && claims[claim] !== null && claims[claim] !== "");
36
+ const tenants = new Set(named.map(([, claim]) => checked(claims[claim])));
37
+ if (tenants.size > 1) {
38
+ throw new TenantContextRefusal("multiple_tenants", "The claims name more than one tenant; a session acts for one tenant at a time.");
39
+ }
40
+ return { tenant: [...tenants][0] ?? null, roles: named.map(([role]) => role) };
41
+ }
42
+ function isRecord(value) {
43
+ return typeof value === "object" && value !== null && !Array.isArray(value);
44
+ }
45
+ export function buildTenantContext(identity, options = {}) {
46
+ const environment = options.environment ?? process.env;
47
+ const explicitTenant = options.explicitTenant ?? null;
48
+ const isUser = isRecord(identity) && isRecord(identity.claims);
49
+ const isIam = isRecord(identity) && !isUser && ("userArn" in identity || "accountId" in identity);
50
+ if (!isUser && !isIam) {
51
+ throw new TenantContextRefusal("unsupported_identity", "The call carries neither a user pool identity nor an IAM identity.");
52
+ }
53
+ const shared = isSharedStack(environment);
54
+ const mode = shared ? "shared" : "dedicated";
55
+ if (isUser && explicitTenant !== null) {
56
+ throw new TenantContextRefusal("explicit_tenant_for_user", "A signed-in caller's tenant comes from its claims, never from an argument.");
57
+ }
58
+ if (isIam && shared && !explicitTenant) {
59
+ throw new TenantContextRefusal("iam_without_tenant", "An IAM call on a shared stack must name its tenant.");
60
+ }
61
+ const { tenant, roles } = isUser ? claimed(identity.claims) : { tenant: null, roles: [] };
62
+ const requested = isIam && explicitTenant ? checked(explicitTenant) : tenant;
63
+ if (shared) {
64
+ if (requested === null)
65
+ throw new TenantContextRefusal("no_tenant_claim", "The caller's token carries no tenant claim.");
66
+ return { tenantId: requested, roles, mode, operator: isIam };
67
+ }
68
+ const fixed = tenantIdFromEnvironment(environment) ?? null;
69
+ if (requested !== null && requested !== fixed) {
70
+ throw new TenantContextRefusal("foreign_tenant", "The call names a tenant other than this stack's fixed tenant.");
71
+ }
72
+ return { tenantId: fixed, roles, mode, operator: isIam };
73
+ }
74
+ export function isIamIdentity(identity) {
75
+ return isRecord(identity) && !isRecord(identity.claims) && ("userArn" in identity || "accountId" in identity);
76
+ }
77
+ /**
78
+ * The one context of an AppSync field event. A signed-in caller's tenant is its role claim and nothing in the arguments is read for it. An IAM
79
+ * caller (the platform operator or a worker) names the tenant as the `tenantId` argument; an operation without that argument cannot be called by
80
+ * IAM on a shared stack, which refuses it before any read.
81
+ */
82
+ export function buildEventTenantContext(event, environment = process.env) {
83
+ const identity = event.identity;
84
+ const named = isIamIdentity(identity) ? event.arguments?.tenantId : undefined;
85
+ return buildTenantContext(identity, { explicitTenant: (named ?? null), environment });
86
+ }
87
+ const acting = new AsyncLocalStorage();
88
+ /** Run one call for `context`: everything it awaits reads the tenant from `currentTenantContext()`, never from the environment. */
89
+ export function actingFor(context, call) {
90
+ return acting.run(context, call);
91
+ }
92
+ export function currentTenantContext() {
93
+ const context = acting.getStore();
94
+ if (!context) {
95
+ throw new TenantContextRefusal("unsupported_identity", "No tenant context: a handler builds one from the event before it reads or writes anything.");
96
+ }
97
+ return context;
98
+ }
@@ -5,6 +5,7 @@
5
5
  * site tenant. The tenant never comes from the request body and is never guessed.
6
6
  * Python twin: src/papyrus_content/tenant_context.py; both read features_backend/fixtures/tenant-context/vectors.json.
7
7
  */
8
+ import { AsyncLocalStorage } from "node:async_hooks";
8
9
  import { isSharedStack, tenantIdFromEnvironment, validateTenantId } from "../../../lib/tenant-keys";
9
10
 
10
11
  export const ROLE_CLAIMS = [
@@ -97,3 +98,35 @@ export function buildTenantContext(identity: Identity, options: TenantContextOpt
97
98
  }
98
99
  return { tenantId: fixed, roles, mode, operator: isIam };
99
100
  }
101
+
102
+ export function isIamIdentity(identity: Identity): boolean {
103
+ return isRecord(identity) && !isRecord(identity.claims) && ("userArn" in identity || "accountId" in identity);
104
+ }
105
+
106
+ type FieldEvent = { identity?: unknown; arguments?: Record<string, unknown> | null };
107
+
108
+ /**
109
+ * The one context of an AppSync field event. A signed-in caller's tenant is its role claim and nothing in the arguments is read for it. An IAM
110
+ * caller (the platform operator or a worker) names the tenant as the `tenantId` argument; an operation without that argument cannot be called by
111
+ * IAM on a shared stack, which refuses it before any read.
112
+ */
113
+ export function buildEventTenantContext(event: FieldEvent, environment: Record<string, string | undefined> = process.env): TenantContext {
114
+ const identity = event.identity as Identity;
115
+ const named = isIamIdentity(identity) ? event.arguments?.tenantId : undefined;
116
+ return buildTenantContext(identity, { explicitTenant: (named ?? null) as string | null, environment });
117
+ }
118
+
119
+ const acting = new AsyncLocalStorage<TenantContext>();
120
+
121
+ /** Run one call for `context`: everything it awaits reads the tenant from `currentTenantContext()`, never from the environment. */
122
+ export function actingFor<T>(context: TenantContext, call: () => T): T {
123
+ return acting.run(context, call);
124
+ }
125
+
126
+ export function currentTenantContext(): TenantContext {
127
+ const context = acting.getStore();
128
+ if (!context) {
129
+ throw new TenantContextRefusal("unsupported_identity", "No tenant context: a handler builds one from the event before it reads or writes anything.");
130
+ }
131
+ return context;
132
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The Amplify data client of one call, scoped to the tenant its context names (TypeScript twin of PapyrusGraphQLAuthoringClient(tenant_id=...)).
3
+ * On a SHARED stack every model that carries a `tenantId` answers only with the caller's tenant's rows: a `get` of another tenant's id returns
4
+ * nothing (so the handler says "not found"), an index query or list drops foreign rows, a create is stamped with the caller's tenant (a payload that
5
+ * names another is refused), and an update or delete first reads the row and refuses one that is not the caller's. On a DEDICATED stack the client
6
+ * is returned as it is: its single tenant is the whole backend.
7
+ */
8
+ import { TENANT_FIELD_MODELS, TENANT_MODELS, tenantScopedValue } from "../../../lib/tenant-keys";
9
+ import type { TenantContext } from "./tenant-context";
10
+
11
+ type Row = Record<string, any>;
12
+ type Result = { data?: Row | Row[] | null; errors?: unknown; nextToken?: string | null };
13
+ type Model = Record<string, (...args: any[]) => Promise<Result>>;
14
+ type ScopableClient = { models: Record<string, any> };
15
+
16
+ const MUTATORS = new Set(["create", "update", "delete"]);
17
+
18
+ function belongs(tenantId: string, row: Row | null | undefined): boolean {
19
+ return !row || row.tenantId === tenantId;
20
+ }
21
+
22
+ function scopedModel(name: string, model: Model, tenantId: string): Model {
23
+ return new Proxy(model, {
24
+ get(target, member: string) {
25
+ const operation = target[member];
26
+ if (typeof operation !== "function") return operation;
27
+ if (member === "get") {
28
+ return async (...args: any[]): Promise<Result> => {
29
+ const result = await operation.apply(target, args);
30
+ return !result.data || Array.isArray(result.data) || belongs(tenantId, result.data) ? result : { ...result, data: null };
31
+ };
32
+ }
33
+ if (member === "create") {
34
+ return async (input: Row, ...rest: any[]): Promise<Result> => {
35
+ if (input.tenantId !== undefined && input.tenantId !== null && input.tenantId !== tenantId) {
36
+ throw new Error(`${name} cannot be created for another tenant.`);
37
+ }
38
+ return operation.call(target, { ...input, tenantId }, ...rest);
39
+ };
40
+ }
41
+ if (MUTATORS.has(member)) {
42
+ return async (input: Row, ...rest: any[]): Promise<Result> => {
43
+ const current = await target.get({ id: input.id });
44
+ if (!current.data || Array.isArray(current.data) || !belongs(tenantId, current.data)) throw new Error(`${name} ${input.id} was not found.`);
45
+ if (input.tenantId !== undefined && input.tenantId !== null && input.tenantId !== tenantId) throw new Error(`${name} cannot move to another tenant.`);
46
+ return operation.call(target, input, ...rest);
47
+ };
48
+ }
49
+ return async (...args: any[]): Promise<Result> => {
50
+ const result = await operation.apply(target, args);
51
+ return Array.isArray(result.data) ? { ...result, data: result.data.filter((row) => belongs(tenantId, row)) } : result;
52
+ };
53
+ },
54
+ });
55
+ }
56
+
57
+ export function tenantScopedClient<Client extends ScopableClient>(client: Client, context: TenantContext): Client {
58
+ if (context.mode !== "shared") return client;
59
+ const tenantId = context.tenantId;
60
+ if (!tenantId) throw new Error("A shared stack's call has a tenant before it has a client.");
61
+ const models = new Proxy(client.models, {
62
+ get(target, name: string) {
63
+ const model = target[name];
64
+ return TENANT_MODELS.has(name) || TENANT_FIELD_MODELS.has(name) ? scopedModel(name, model, tenantId) : model;
65
+ },
66
+ });
67
+ return { ...client, models } as Client;
68
+ }
69
+
70
+ /** A record id that is the same for every tenant today (a singleton such as the Newsroom summary), as this stack stores it. */
71
+ export function scopedRecordId(context: TenantContext, id: string): string {
72
+ return context.mode === "shared" && context.tenantId ? tenantScopedValue(context.tenantId, id) : id;
73
+ }
74
+
75
+ const NEWSROOM_SUMMARY_BASE_ID = "knowledge-raw-payload-newsroom-summary-current";
76
+
77
+ /** The id of the call's tenant's Newsroom summary snapshot: the one record id every tenant would otherwise share. */
78
+ export function newsroomSummaryPayloadId(context: TenantContext): string {
79
+ return scopedRecordId(context, NEWSROOM_SUMMARY_BASE_ID);
80
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * The tenant claims a session token carries (PPY-0bb0fd, docs/multi-tenancy.md "Session claims").
3
+ *
4
+ * One claim per role the person holds on the one tenant the session acts for, each holding the tenant id. The role names and
5
+ * claim names are the ones `shared/tenant-context.ts` reads, so a token built here is exactly what that builder accepts.
6
+ */
7
+ import { isSharedStack, tenantIdFromEnvironment, validateTenantId } from "../../../lib/tenant-keys";
8
+ import { TENANCY_MODELS_ENVIRONMENT_VARIABLE } from "./environment";
9
+ import { ROLE_CLAIMS, type TenantRole } from "../shared/tenant-context";
10
+
11
+ /** A membership counts only while its status is this value (src/papyrus_content/tenant_records.py). */
12
+ export const ACTIVE_MEMBERSHIP_STATUS = "active";
13
+
14
+ /** The Cognito groups a dedicated stack maps to a role claim; there is no group for `member`. */
15
+ const GROUP_ROLES: readonly TenantRole[] = ["admin", "editor", "curator"];
16
+
17
+ export type Row = Record<string, unknown>;
18
+ export type TenancyModel = "TenantMembership" | "TenantSelection";
19
+ /** Reads one row of a tenancy model by its id (a GetItem), or null when there is none. */
20
+ export type ItemReader = (model: TenancyModel, id: string) => Promise<Row | null>;
21
+
22
+ export type ClaimEnvironment = {
23
+ shared: boolean;
24
+ /** A dedicated stack's fixed tenant; null when it has none, and always null on a shared stack. */
25
+ fixedTenantId: string | null;
26
+ /** Whether the TenantMembership and TenantSelection models are deployed on this stack. */
27
+ tenancyModels: boolean;
28
+ };
29
+
30
+ export function claimEnvironment(environment: Record<string, string | undefined>): ClaimEnvironment {
31
+ const shared = isSharedStack(environment);
32
+ return {
33
+ shared,
34
+ fixedTenantId: shared ? null : tenantIdFromEnvironment(environment) ?? null,
35
+ tenancyModels: environment[TENANCY_MODELS_ENVIRONMENT_VARIABLE]?.trim() === "true",
36
+ };
37
+ }
38
+
39
+ function validTenantId(value: unknown): string | null {
40
+ if (typeof value !== "string") return null;
41
+ try {
42
+ return validateTenantId(value);
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+
48
+ /** The role an active membership row of this person and tenant grants, or null. The row's own fields must agree with the key. */
49
+ export function membershipRole(row: Row | null, tenantId: string, userSub: string): TenantRole | null {
50
+ if (!row || row.status !== ACTIVE_MEMBERSHIP_STATUS || row.tenantId !== tenantId || row.userSub !== userSub) return null;
51
+ return ROLE_CLAIMS.find(([role]) => role === row.role)?.[0] ?? null;
52
+ }
53
+
54
+ /**
55
+ * The tenant this session acts for. A shared stack takes the person's stored selection (the Google flow cannot pass one, so
56
+ * the choice is written first and read here); a stored value that is not a tenant id selects nothing. A dedicated stack acts
57
+ * for its fixed tenant whatever was selected.
58
+ */
59
+ export async function sessionTenant(environment: ClaimEnvironment, userSub: string, read: ItemReader): Promise<string | null> {
60
+ if (!environment.shared) return environment.fixedTenantId;
61
+ if (!environment.tenancyModels) return null;
62
+ const selection = await read("TenantSelection", userSub);
63
+ return validTenantId(selection?.selectedTenantId);
64
+ }
65
+
66
+ /** Roles a person holds on a dedicated stack through their Cognito groups. A shared stack never reads groups for a tenant. */
67
+ export function rolesFromGroups(groups: readonly string[]): TenantRole[] {
68
+ return GROUP_ROLES.filter((role) => groups.includes(role));
69
+ }
70
+
71
+ /**
72
+ * Every claim for one sign-in or refresh: `{papyrus_tenant_<role>: tenantId}` for each role held on the session's tenant, or
73
+ * nothing when the person has no tenant, no active membership there and (on a dedicated stack) no matching group.
74
+ */
75
+ export async function buildTenantClaims(
76
+ environment: ClaimEnvironment,
77
+ person: { userSub: string; groups: readonly string[] },
78
+ read: ItemReader,
79
+ ): Promise<Record<string, string>> {
80
+ const tenantId = await sessionTenant(environment, person.userSub, read);
81
+ if (tenantId === null) return {};
82
+ const roles = new Set<TenantRole>(environment.shared ? [] : rolesFromGroups(person.groups));
83
+ if (environment.tenancyModels) {
84
+ const role = membershipRole(await read("TenantMembership", `${tenantId}#${person.userSub}`), tenantId, person.userSub);
85
+ if (role) roles.add(role);
86
+ }
87
+ const claims: Record<string, string> = {};
88
+ for (const [role, claim] of ROLE_CLAIMS) if (roles.has(role)) claims[claim] = tenantId;
89
+ return claims;
90
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Set to "true" by the site backend when the `tenancy` model group is deployed (a bootstrap deploy leaves it out), which is
3
+ * when TenantMembership and TenantSelection exist to be read. Without it the function reads no table.
4
+ * Its own file because the backend definition (amplify/auth/tenant-session-claims.ts) needs it and the package compiles that
5
+ * side separately from the handler side (packages/papyrus/scripts/stage.mjs).
6
+ */
7
+ export const TENANCY_MODELS_ENVIRONMENT_VARIABLE = "PAPYRUS_TENANT_RECORDS_DEPLOYED";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Set to "true" by the site backend when the `tenancy` model group is deployed (a bootstrap deploy leaves it out), which is
3
+ * when TenantMembership and TenantSelection exist to be read. Without it the function reads no table.
4
+ * Its own file because the backend definition (amplify/auth/tenant-session-claims.ts) needs it and the package compiles that
5
+ * side separately from the handler side (packages/papyrus/scripts/stage.mjs).
6
+ */
7
+ export const TENANCY_MODELS_ENVIRONMENT_VARIABLE = "PAPYRUS_TENANT_RECORDS_DEPLOYED";
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Cognito pre-token-generation trigger, event version 2 (PPY-0bb0fd). On every sign-in and refresh it adds the tenant role
3
+ * claims (claims.ts) to the access token and the ID token, beside the person's Cognito groups, which it never touches.
4
+ * It reads only the TenantSelection and TenantMembership rows of this stack, never Prospectus. A failed read fails the
5
+ * token request: a guessed answer would grant or withhold access without anyone knowing.
6
+ */
7
+ import { getLambdaDataClient, LAMBDA_DATA_AUTH_MODE } from "../shared/lambda-data-client";
8
+ import { buildTenantClaims, claimEnvironment, type ItemReader, type Row } from "./claims";
9
+
10
+ export type PreTokenGenerationV2Event = {
11
+ request: {
12
+ userAttributes: Record<string, string>;
13
+ groupConfiguration?: { groupsToOverride?: string[] };
14
+ };
15
+ response: {
16
+ claimsAndScopeOverrideDetails?: {
17
+ idTokenGeneration?: { claimsToAddOrOverride?: Record<string, string> };
18
+ accessTokenGeneration?: { claimsToAddOrOverride?: Record<string, string> };
19
+ };
20
+ };
21
+ };
22
+
23
+ export function createHandler(read: ItemReader, environment: () => Record<string, string | undefined> = () => process.env) {
24
+ return async function handler<Event extends PreTokenGenerationV2Event>(event: Event): Promise<Event> {
25
+ const userSub = event.request.userAttributes.sub;
26
+ if (!userSub) throw new Error("The token event carries no sub, so no tenant can be chosen for it.");
27
+ const claims = await buildTenantClaims(
28
+ claimEnvironment(environment()),
29
+ { userSub, groups: event.request.groupConfiguration?.groupsToOverride ?? [] },
30
+ read,
31
+ );
32
+ if (Object.keys(claims).length > 0) {
33
+ event.response.claimsAndScopeOverrideDetails = {
34
+ ...event.response.claimsAndScopeOverrideDetails,
35
+ idTokenGeneration: { claimsToAddOrOverride: claims },
36
+ accessTokenGeneration: { claimsToAddOrOverride: claims },
37
+ };
38
+ }
39
+ return event;
40
+ };
41
+ }
42
+
43
+ /**
44
+ * One GetItem through the stack's own data API with the function's IAM role (the same wiring as manage-user-role). The function
45
+ * sits in the auth stack, which the data API's user pool depends on, so it cannot name the tables directly without a cycle
46
+ * between the two stacks; the schema grants it query access instead (`functionGrants` in amplify/data/schema.ts).
47
+ */
48
+ const readDataItem: ItemReader = async (model, id) => {
49
+ const client = await getLambdaDataClient();
50
+ const options = { authMode: LAMBDA_DATA_AUTH_MODE };
51
+ const { data, errors } = model === "TenantSelection" ? await client.models.TenantSelection.get({ id }, options) : await client.models.TenantMembership.get({ id }, options);
52
+ if (errors?.length) throw new Error(`Reading ${model} ${id} failed: ${errors.map((error: { message?: string }) => error.message).join("; ")}`);
53
+ return (data as Row | null | undefined) ?? null;
54
+ };
55
+
56
+ export const handler = createHandler(readDataItem);
@@ -0,0 +1,12 @@
1
+ import { defineFunction } from "@aws-amplify/backend";
2
+ /**
3
+ * Cognito's pre-token-generation trigger (PPY-0bb0fd). `amplify/auth/tenant-session-claims.ts` rewires it to event version 2
4
+ * (so the claims land on the access token) and gives it read access to two tenancy tables.
5
+ */
6
+ export const tenantClaims = defineFunction({
7
+ name: "papyrus-tenant-claims",
8
+ entry: "./handler.ts",
9
+ timeoutSeconds: 5,
10
+ memoryMB: 256,
11
+ resourceGroupName: "auth",
12
+ });
@@ -0,0 +1,13 @@
1
+ import { defineFunction } from "@aws-amplify/backend";
2
+
3
+ /**
4
+ * Cognito's pre-token-generation trigger (PPY-0bb0fd). `amplify/auth/tenant-session-claims.ts` rewires it to event version 2
5
+ * (so the claims land on the access token) and gives it read access to two tenancy tables.
6
+ */
7
+ export const tenantClaims = defineFunction({
8
+ name: "papyrus-tenant-claims",
9
+ entry: "./handler.ts",
10
+ timeoutSeconds: 5,
11
+ memoryMB: 256,
12
+ resourceGroupName: "auth",
13
+ });
@@ -4,6 +4,7 @@ import { Architecture, Function as LambdaFunction, Runtime } from "aws-cdk-lib/a
4
4
  import { SqsEventSource } from "aws-cdk-lib/aws-lambda-event-sources";
5
5
  import { CfnSchedule } from "aws-cdk-lib/aws-scheduler";
6
6
  import { Queue, QueueEncryption } from "aws-cdk-lib/aws-sqs";
7
+ import { connectToSiteApi } from "../../site-api-access.js";
7
8
  export const NEWSLETTER_WORKER_HANDLER = "papyrus_content.newsletter.worker.handler";
8
9
  /** The worker mails up to 50 subscribers per message at the SES send rate; the visibility timeout is six times this. */
9
10
  export const WORKER_TIMEOUT_SECONDS = 180;
@@ -62,7 +63,7 @@ export function wireSending(inputs) {
62
63
  lambda.addEnvironment("SCHEDULER_ROLE_ARN", schedulerRole.roleArn);
63
64
  lambda.addEnvironment("QUEUE_URL", queue.queueUrl);
64
65
  lambda.addEnvironment("CONTENT_ACTIONS_FUNCTION", contentActions.functionName);
65
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
66
+ connectToSiteApi(lambda, context.graphqlEndpoint);
66
67
  queue.grantSendMessages(lambda);
67
68
  contentActions.grantInvoke(lambda);
68
69
  lambda.addToRolePolicy(new PolicyStatement({ effect: Effect.ALLOW, actions: ["ssm:GetParameter"], resources: postalAddressParameterArns(stack, config.siteId) }));
@@ -7,6 +7,7 @@ import { CfnSchedule } from "aws-cdk-lib/aws-scheduler";
7
7
  import { Queue, QueueEncryption } from "aws-cdk-lib/aws-sqs";
8
8
  import type { PluginWiringContext } from "../types";
9
9
  import type { NewsletterConfig, RoundupList } from "./config";
10
+ import { connectToSiteApi } from "../../site-api-access";
10
11
 
11
12
  export const NEWSLETTER_WORKER_HANDLER = "papyrus_content.newsletter.worker.handler";
12
13
  /** The worker mails up to 50 subscribers per message at the SES send rate; the visibility timeout is six times this. */
@@ -90,7 +91,7 @@ export function wireSending(inputs: SendingInputs): { queue: Queue; deadLetterQu
90
91
  lambda.addEnvironment("SCHEDULER_ROLE_ARN", schedulerRole.roleArn);
91
92
  lambda.addEnvironment("QUEUE_URL", queue.queueUrl);
92
93
  lambda.addEnvironment("CONTENT_ACTIONS_FUNCTION", contentActions.functionName);
93
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
94
+ connectToSiteApi(lambda, context.graphqlEndpoint);
94
95
 
95
96
  queue.grantSendMessages(lambda);
96
97
  contentActions.grantInvoke(lambda);
@@ -16,6 +16,7 @@ import { SecureStringParameter } from "../newsletter/secure-string-parameter.js"
16
16
  import { ALARM_MINIMUM_SENDS, BOUNCE_RATE_THRESHOLD, COMPLAINT_RATE_THRESHOLD } from "../newsletter/papyrus.plugin.js";
17
17
  import { functionArn, postalAddressParameterArns } from "../newsletter/sending.js";
18
18
  import { resolveNotificationsConfig } from "./config.js";
19
+ import { siteApiEnvironment } from "../../site-api-access.js";
19
20
  export { resolveNotificationsConfig };
20
21
  export const NOTIFICATIONS_OUTPUT_KEY = "notifications";
21
22
  /** Set on the site's content-actions function: it invokes the router function (`story-published`) after a real publish. Unset: no notices. */
@@ -189,7 +190,7 @@ export const notificationsPlugin = {
189
190
  const environment = {
190
191
  ...notificationsEnvironment(config, { table: table.tableName, operators: operatorsParameter, key: keyParameter.parameterName }),
191
192
  EMAIL_QUEUE_URL: emailQueue.queueUrl,
192
- PAPYRUS_GRAPHQL_ENDPOINT: context.graphqlEndpoint,
193
+ ...siteApiEnvironment(context.graphqlEndpoint),
193
194
  };
194
195
  const common = { runtime: Runtime.PYTHON_3_12, architecture: Architecture.ARM_64, code, environment };
195
196
  const router = new LambdaFunction(stack, "RouterFunction", {
@@ -17,6 +17,7 @@ import { ALARM_MINIMUM_SENDS, BOUNCE_RATE_THRESHOLD, COMPLAINT_RATE_THRESHOLD }
17
17
  import { functionArn, postalAddressParameterArns } from "../newsletter/sending";
18
18
  import type { PapyrusPlugin, PluginManifest, PluginWiringContext } from "../types";
19
19
  import { resolveNotificationsConfig, type NotificationsConfig } from "./config";
20
+ import { siteApiEnvironment } from "../../site-api-access";
20
21
 
21
22
  export { resolveNotificationsConfig };
22
23
  export type { NotificationsConfig };
@@ -209,7 +210,7 @@ export const notificationsPlugin: PapyrusPlugin<NotificationsConfig, Record<stri
209
210
  const environment = {
210
211
  ...notificationsEnvironment(config, { table: table.tableName, operators: operatorsParameter, key: keyParameter.parameterName }),
211
212
  EMAIL_QUEUE_URL: emailQueue.queueUrl,
212
- PAPYRUS_GRAPHQL_ENDPOINT: context.graphqlEndpoint,
213
+ ...siteApiEnvironment(context.graphqlEndpoint),
213
214
  };
214
215
  const common = { runtime: Runtime.PYTHON_3_12, architecture: Architecture.ARM_64, code, environment };
215
216
  const router = new LambdaFunction(stack, "RouterFunction", {
@@ -3,6 +3,7 @@ import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
3
3
  import { signupSubmit } from "./function/resource.js";
4
4
  import { signupSchemaDefinitions } from "./schema.js";
5
5
  import { SIGNUP_MUTATION_FIELD, WAF_MINIMUM_RATE_LIMIT, addSignupRateLimit } from "./waf.js";
6
+ import { connectToSiteApi } from "../../site-api-access.js";
6
7
  const FORM_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
7
8
  const KNOWN_KEYS = new Set(["name", "forms", "addressLimitPerMinute", "waf"]);
8
9
  export const signupManifest = {
@@ -41,7 +42,7 @@ export const signupPlugin = {
41
42
  wire(backend, config, context) {
42
43
  const lambda = backend.signupSubmit.resources.lambda;
43
44
  const stack = Stack.of(lambda);
44
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
45
+ connectToSiteApi(lambda, context.graphqlEndpoint);
45
46
  lambda.addEnvironment("PAPYRUS_SIGNUP_FORMS", config.forms.join(","));
46
47
  lambda.addEnvironment("PAPYRUS_SIGNUP_ADDRESS_LIMIT", String(config.addressLimitPerMinute));
47
48
  lambda.addToRolePolicy(new PolicyStatement({
@@ -5,6 +5,7 @@ import type { PapyrusPlugin, PluginManifest, PluginRequest, PluginWiringContext
5
5
  import { signupSubmit } from "./function/resource";
6
6
  import { signupSchemaDefinitions } from "./schema";
7
7
  import { SIGNUP_MUTATION_FIELD, WAF_MINIMUM_RATE_LIMIT, addSignupRateLimit } from "./waf";
8
+ import { connectToSiteApi } from "../../site-api-access";
8
9
 
9
10
  export type SignupPluginConfig = {
10
11
  /** Form names the site accepts. A submission naming any other form is rejected. */
@@ -54,7 +55,7 @@ export const signupPlugin: PapyrusPlugin<SignupPluginConfig, { signupSubmit: typ
54
55
  wire(backend, config, context: PluginWiringContext) {
55
56
  const lambda = backend.signupSubmit.resources.lambda as LambdaFunction;
56
57
  const stack = Stack.of(lambda);
57
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", context.graphqlEndpoint);
58
+ connectToSiteApi(lambda, context.graphqlEndpoint);
58
59
  lambda.addEnvironment("PAPYRUS_SIGNUP_FORMS", config.forms.join(","));
59
60
  lambda.addEnvironment("PAPYRUS_SIGNUP_ADDRESS_LIMIT", String(config.addressLimitPerMinute));
60
61
  lambda.addToRolePolicy(
@@ -0,0 +1,53 @@
1
+ import { Duration } from "aws-cdk-lib";
2
+ import * as cloudwatch from "aws-cdk-lib/aws-cloudwatch";
3
+ import { shortHash } from "./isolation.js";
4
+ export const DYNAMODB_TABLES_PER_ALARM = 5;
5
+ const minutes = (settings) => Duration.minutes(settings.alarms.periodMinutes);
6
+ function metricAlarm(scope, plan, kind, key, metric, threshold, description, operator = cloudwatch.ComparisonOperator.GREATER_THAN_OR_EQUAL_TO_THRESHOLD) {
7
+ return new cloudwatch.Alarm(scope, `${kind}${shortHash(key, 8)}`, {
8
+ alarmName: `${plan.stackPrefix}-${kind}-${key.replace(new RegExp(`^${plan.stackPrefix}-`), "").slice(0, 60)}`.slice(0, 255),
9
+ alarmDescription: description,
10
+ metric,
11
+ threshold,
12
+ evaluationPeriods: 1,
13
+ comparisonOperator: operator,
14
+ treatMissingData: cloudwatch.TreatMissingData.NOT_BREACHING,
15
+ });
16
+ }
17
+ export function addSharedStackAlarms(scope, plan, settings, inputs) {
18
+ const period = minutes(settings);
19
+ const alarms = [];
20
+ const where = `the ${plan.tier} shared stack`;
21
+ for (const target of inputs.functions) {
22
+ const dimensionsMap = { FunctionName: target.functionName };
23
+ const lambdaMetric = (metricName, statistic) => new cloudwatch.Metric({ namespace: "AWS/Lambda", metricName, dimensionsMap, statistic, period });
24
+ alarms.push(metricAlarm(scope, plan, "errors", target.functionName, lambdaMetric("Errors", "Sum"), settings.alarms.functionErrors, `${target.functionName} in ${where} returned errors.`), metricAlarm(scope, plan, "throttles", target.functionName, lambdaMetric("Throttles", "Sum"), settings.alarms.functionThrottles, `${target.functionName} in ${where} was throttled: it reached its reserved concurrency.`));
25
+ if (target.reserved !== undefined) {
26
+ // Concurrency against the reserved share: the reservation is also this function's ceiling, so a share of it is the early warning.
27
+ const threshold = Math.max(1, Math.ceil(target.reserved * settings.alarms.concurrencyShareOfReserved));
28
+ alarms.push(metricAlarm(scope, plan, "concurrency", target.functionName, lambdaMetric("ConcurrentExecutions", "Maximum"), threshold, `${target.functionName} in ${where} reached ${settings.alarms.concurrencyShareOfReserved * 100}% of its reserved concurrency of ${target.reserved}.`));
29
+ }
30
+ }
31
+ const appSync = (metricName) => new cloudwatch.Metric({ namespace: "AWS/AppSync", metricName, dimensionsMap: { GraphQLAPIId: inputs.appSyncApiId }, statistic: "Sum", period });
32
+ alarms.push(metricAlarm(scope, plan, "appsync-5xx", "api", appSync("5XXError"), settings.alarms.appSyncServerErrors, `The AppSync API of ${where} returned server errors.`),
33
+ // AppSync has no throttle metric: a throttled request is answered 429 and counted in 4XXError.
34
+ 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.`));
35
+ for (let index = 0; index < inputs.tableNames.length; index += DYNAMODB_TABLES_PER_ALARM) {
36
+ const chunk = inputs.tableNames.slice(index, index + DYNAMODB_TABLES_PER_ALARM);
37
+ const usingMetrics = {};
38
+ chunk.forEach((tableName, position) => {
39
+ for (const metricName of ["ReadThrottleEvents", "WriteThrottleEvents"]) {
40
+ usingMetrics[`m${position}${metricName[0].toLowerCase()}`] = new cloudwatch.Metric({ namespace: "AWS/DynamoDB", metricName, dimensionsMap: { TableName: tableName }, statistic: "Sum", period });
41
+ }
42
+ });
43
+ const group = `group-${index / DYNAMODB_TABLES_PER_ALARM + 1}`;
44
+ alarms.push(metricAlarm(scope, plan, "dynamodb-throttles", group, new cloudwatch.MathExpression({ expression: "SUM(METRICS())", usingMetrics, period, label: "Throttled reads and writes" }), settings.alarms.dynamoDbThrottledRequests, `DynamoDB throttled reads or writes on ${chunk.length} tables of ${where}.`));
45
+ }
46
+ if (inputs.projectionDeadLetterQueueName !== undefined) {
47
+ alarms.push(metricAlarm(scope, plan, "projection-dlq", "queue", new cloudwatch.Metric({ namespace: "AWS/SQS", metricName: "ApproximateNumberOfMessagesVisible", dimensionsMap: { QueueName: inputs.projectionDeadLetterQueueName }, statistic: "Maximum", period }), settings.alarms.projectionDeadLetterMessages, `Failed projections are waiting in the dead-letter queue of ${where}.`));
48
+ }
49
+ if (inputs.distributionId !== undefined) {
50
+ alarms.push(metricAlarm(scope, plan, "purged-paths", inputs.distributionId, new cloudwatch.Metric({ namespace: "Papyrus/Edge", metricName: "InvalidatedPaths", dimensionsMap: { DistributionId: inputs.distributionId }, statistic: "Sum", period: Duration.days(7) }), settings.alarms.purgedPathsPerWeek, `The shared distribution of ${where} purged many paths in a week (billable past the free allowance).`));
51
+ }
52
+ return alarms;
53
+ }