@anthusai/papyrus 5.111.0 → 5.112.0-next.1

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
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { hashtagsInMessageText } from "../../../lib/message-hashtags";
3
3
  import { conceptKeysForHashtag } from "../../../lib/wiki";
4
4
  import { REFERENCE_LINK_FEED_KEY, globalKey } from "../../../lib/tenant-knowledge-keys";
5
+ import { currentTenantContext } from "../shared/tenant-context";
5
6
 
6
7
  export const MESSAGE_CONCEPT_EDGE_KIND = "message.concept";
7
8
  export const MESSAGE_CONCEPT_FEED_KEY = REFERENCE_LINK_FEED_KEY;
@@ -96,7 +97,7 @@ export async function linkMessageHashtags(
96
97
  reviewRecommended: false,
97
98
  importedAt: input.now,
98
99
  updatedAt: input.now,
99
- newsroomFeedKey: globalKey(MESSAGE_CONCEPT_FEED_KEY),
100
+ newsroomFeedKey: globalKey(MESSAGE_CONCEPT_FEED_KEY, currentTenantContext().tenantId),
100
101
  metadata: JSON.stringify(metadata),
101
102
  },
102
103
  existing !== null,
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { changeReasonAfterNewDescription } from "./knowledge-review.js";
3
3
  import { REFERENCE_LINK_FEED_KEY, SEMANTIC_NODE_FEED_KEY, globalKey } from "../../../lib/tenant-knowledge-keys.js";
4
+ import { currentTenantContext } from "../shared/tenant-context.js";
4
5
  export const REFERENCE_LINK_KIND = "reference.link";
5
6
  export const REFERENCE_CONCEPT_KIND = "reference.concept";
6
7
  export const ITEM_CONCEPT_KIND = "item.concept";
@@ -144,7 +145,7 @@ export function buildHumanEdgeRow(input) {
144
145
  reviewRecommended: false,
145
146
  importedAt: input.now,
146
147
  updatedAt: input.now,
147
- newsroomFeedKey: globalKey(REFERENCE_LINK_FEED_KEY),
148
+ newsroomFeedKey: globalKey(REFERENCE_LINK_FEED_KEY, currentTenantContext().tenantId),
148
149
  metadata: JSON.stringify(metadata),
149
150
  };
150
151
  }
@@ -261,7 +262,7 @@ export async function ensureEditorConcept(store, name, callerSub, now, options =
261
262
  const node = {
262
263
  id: `${lineageId}-v1`, lineageId, versionNumber: 1, versionState: "current", versionCreatedAt: now, versionCreatedBy: callerSub, changeReason: options.origin && options.origin !== "newsroom" ? `Invented by an editor with a hashtag (via ${options.origin})` : "Invented by an editor with a hashtag",
263
264
  nodeKey: editorConceptKey(slug), nodeKind: EDITOR_CONCEPT_KIND, displayName, status: "accepted", aliases: [], createdAt: now, updatedAt: now,
264
- newsroomFeedKey: globalKey(SEMANTIC_NODE_FEED_KEY),
265
+ newsroomFeedKey: globalKey(SEMANTIC_NODE_FEED_KEY, currentTenantContext().tenantId),
265
266
  };
266
267
  await store.createSemanticNode(node); // false: it exists now (a second tap); read it back either way
267
268
  const made = await store.getSemanticNode(lineageId);
@@ -1,6 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { changeReasonAfterNewDescription } from "./knowledge-review";
3
3
  import { REFERENCE_LINK_FEED_KEY, SEMANTIC_NODE_FEED_KEY, globalKey } from "../../../lib/tenant-knowledge-keys";
4
+ import { currentTenantContext } from "../shared/tenant-context";
4
5
 
5
6
  export const REFERENCE_LINK_KIND = "reference.link";
6
7
  export const REFERENCE_CONCEPT_KIND = "reference.concept";
@@ -181,7 +182,7 @@ export function buildHumanEdgeRow(input: { relationId: string; kind: string; pre
181
182
  reviewRecommended: false,
182
183
  importedAt: input.now,
183
184
  updatedAt: input.now,
184
- newsroomFeedKey: globalKey(REFERENCE_LINK_FEED_KEY),
185
+ newsroomFeedKey: globalKey(REFERENCE_LINK_FEED_KEY, currentTenantContext().tenantId),
185
186
  metadata: JSON.stringify(metadata),
186
187
  };
187
188
  }
@@ -289,7 +290,7 @@ export async function ensureEditorConcept(store: ReferenceLinkStore, name: strin
289
290
  const node = {
290
291
  id: `${lineageId}-v1`, lineageId, versionNumber: 1, versionState: "current", versionCreatedAt: now, versionCreatedBy: callerSub, changeReason: options.origin && options.origin !== "newsroom" ? `Invented by an editor with a hashtag (via ${options.origin})` : "Invented by an editor with a hashtag",
291
292
  nodeKey: editorConceptKey(slug), nodeKind: EDITOR_CONCEPT_KIND, displayName, status: "accepted", aliases: [], createdAt: now, updatedAt: now,
292
- newsroomFeedKey: globalKey(SEMANTIC_NODE_FEED_KEY),
293
+ newsroomFeedKey: globalKey(SEMANTIC_NODE_FEED_KEY, currentTenantContext().tenantId),
293
294
  };
294
295
  await store.createSemanticNode(node); // false: it exists now (a second tap); read it back either way
295
296
  const made = await store.getSemanticNode(lineageId);
@@ -3,6 +3,7 @@ import { Platform } from "aws-cdk-lib/aws-ecr-assets";
3
3
  import { Repository } from "aws-cdk-lib/aws-ecr";
4
4
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
5
5
  import { Architecture, CfnEventSourceMapping, DockerImageCode, DockerImageFunction } from "aws-cdk-lib/aws-lambda";
6
+ import { siteApiEnvironment } from "../../site-api-access.js";
6
7
  export class ConsoleChatResponderStack extends NestedStack {
7
8
  responderFunction;
8
9
  constructor(scope, id, props) {
@@ -12,7 +13,7 @@ export class ConsoleChatResponderStack extends NestedStack {
12
13
  PAPYRUS_MESSAGE_TABLE_NAME: props.messageTable.tableName,
13
14
  PAPYRUS_MESSAGE_THREAD_TABLE_NAME: props.threadTable.tableName,
14
15
  PAPYRUS_MESSAGE_THREAD_SEQUENCE_INDEX_NAME: "messagesByThreadSequence",
15
- PAPYRUS_GRAPHQL_ENDPOINT: props.graphqlEndpoint,
16
+ ...siteApiEnvironment(props.graphqlEndpoint),
16
17
  PAPYRUS_CONSOLE_RESPONSE_TARGET: responseTarget,
17
18
  PAPYRUS_CONSOLE_MODEL: props.model?.trim() || process.env.PAPYRUS_CONSOLE_MODEL || "gpt-6-luna",
18
19
  PAPYRUS_CONSOLE_CONTEXT_CACHE_ROOT: "/tmp/papyrus-console/thread-context",
@@ -5,6 +5,7 @@ import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
5
5
  import { Architecture, CfnEventSourceMapping, DockerImageCode, DockerImageFunction } from "aws-cdk-lib/aws-lambda";
6
6
  import type { ITable } from "aws-cdk-lib/aws-dynamodb";
7
7
  import { Construct } from "constructs";
8
+ import { siteApiEnvironment } from "../../site-api-access";
8
9
 
9
10
  export type ConsoleChatResponderStackProps = NestedStackProps & {
10
11
  messageTable: ITable;
@@ -28,7 +29,7 @@ export class ConsoleChatResponderStack extends NestedStack {
28
29
  PAPYRUS_MESSAGE_TABLE_NAME: props.messageTable.tableName,
29
30
  PAPYRUS_MESSAGE_THREAD_TABLE_NAME: props.threadTable.tableName,
30
31
  PAPYRUS_MESSAGE_THREAD_SEQUENCE_INDEX_NAME: "messagesByThreadSequence",
31
- PAPYRUS_GRAPHQL_ENDPOINT: props.graphqlEndpoint,
32
+ ...siteApiEnvironment(props.graphqlEndpoint),
32
33
  PAPYRUS_CONSOLE_RESPONSE_TARGET: responseTarget,
33
34
  PAPYRUS_CONSOLE_MODEL: props.model?.trim() || process.env.PAPYRUS_CONSOLE_MODEL || "gpt-6-luna",
34
35
  PAPYRUS_CONSOLE_CONTEXT_CACHE_ROOT: "/tmp/papyrus-console/thread-context",
@@ -7,6 +7,7 @@ from typing import Any
7
7
  from papyrus_content import request_meter
8
8
  from papyrus_content.edge_invalidation import distribution_ids_from_environment, invalidate_revalidated_paths
9
9
  from papyrus_content.graphql_authoring import create_authoring_client
10
+ from papyrus_content.tenant_context import acting_for, build_event_tenant_context, build_invocation_tenant_context, current_tenant_context
10
11
  from papyrus_content.markus_renderer.body_features import install_body_features
11
12
  from papyrus_content.markus_renderer.derive import derive_body
12
13
  from papyrus_content.projection.deploy_render import deploy_render, drift_metric_line
@@ -68,6 +69,12 @@ def parse_input(raw: Any) -> dict:
68
69
  return parsed
69
70
 
70
71
 
72
+ def authoring_client():
73
+ """The authoring client of the call being served. Its tenant is the one in the context the handler built from the event, never the environment's."""
74
+ client, _claims = create_authoring_client(current_tenant_context().tenant_id)
75
+ return client
76
+
77
+
71
78
  def actor_from_event(event: dict) -> str:
72
79
  identity = event.get("identity") or {}
73
80
  return identity.get("username") or identity.get("sub") or "unknown"
@@ -145,12 +152,19 @@ def send_to_projection_dead_letter_queue(task: dict, error: str) -> None:
145
152
  pass
146
153
 
147
154
 
155
+ def stamped_with_tenant(task: dict) -> dict:
156
+ """A task carries the tenant of the call that scheduled it, so a shared stack's later invocation names it (a dedicated stack with no tenant adds nothing)."""
157
+ tenant_id = current_tenant_context().tenant_id
158
+ return {**task, "tenantId": tenant_id} if tenant_id else task
159
+
160
+
148
161
  def schedule_projection_task(task: dict, error: str) -> bool:
149
162
  """Run a projection task later, in this same function, as an asynchronous invocation.
150
163
 
151
164
  The function has an on-failure destination (the dead letter queue), so a task
152
165
  that keeps failing ends up there for ``papyrus ops content project --reconcile``.
153
166
  """
167
+ task = stamped_with_tenant(task)
154
168
  function_name = (os.environ.get("AWS_LAMBDA_FUNCTION_NAME") or "").strip()
155
169
  if not function_name:
156
170
  send_to_projection_dead_letter_queue(task, error)
@@ -320,7 +334,7 @@ def refresh_site_pages_action(arguments: dict, who: str = "content-actions") ->
320
334
  return {"ok": False, "operation": name, "error": {"code": "not_projected", "message": "This site does not project its pages to S3, so there is no edge cache to refresh from here."}}
321
335
  operation = PAGE_REFRESH_OPERATIONS.get(name)
322
336
  if operation is None:
323
- return run_page_refresh(name, inputs, refresh_service(None, who))
337
+ return run_page_refresh(name, inputs, refresh_service(authoring_client(), who))
324
338
  if inputs.pop("jobStatus", False) is True:
325
339
  return rerender_status_action(inputs)
326
340
  background = inputs.pop("async", False) is True
@@ -328,7 +342,7 @@ def refresh_site_pages_action(arguments: dict, who: str = "content-actions") ->
328
342
  validate_page_refresh(operation, inputs)
329
343
  except RefreshError as error:
330
344
  return {"ok": False, "operation": name, "error": {"code": error.code, "message": error.message}}
331
- client, _claims = create_authoring_client()
345
+ client = authoring_client()
332
346
  service = refresh_service(client, who)
333
347
  if name == "site_rerender_pages" and (inputs["scope"] != "story" or background) and not inputs.get("dryRun"):
334
348
  checked = run_page_refresh(name, {**inputs, "dryRun": True}, service) # the guard first: nothing is scheduled that would be refused or is only a preview
@@ -398,12 +412,13 @@ def run_home_page_snapshot_task(client, task: dict | None = None) -> dict:
398
412
  grow with the corpus (``papyrus_content/home_page/incremental.py``). Any other run reads the whole corpus and leaves the private state for the next one.
399
413
  """
400
414
  context = projection_context(client)
415
+ tenant_id = client.tenant_id
401
416
  state_store, dirty_store, batch = home_page_stores_for(task or {})
402
417
  report = run_home_page_snapshot(
403
418
  context,
404
419
  client,
405
420
  home_page_settings_of(context.projector),
406
- client_factory=lambda: create_authoring_client()[0],
421
+ client_factory=lambda: create_authoring_client(tenant_id)[0], # worker threads do not inherit the call's context: the tenant is passed in
407
422
  workers=HOME_PAGE_SNAPSHOT_WORKERS,
408
423
  state_store=state_store,
409
424
  dirty=batch,
@@ -604,7 +619,7 @@ def run_page_refresh_rerender_task(client, task: dict) -> dict:
604
619
 
605
620
 
606
621
  def _run_projection_task(task: dict, lambda_context=None) -> dict:
607
- client, _claims = create_authoring_client()
622
+ client = authoring_client()
608
623
  if task.get("task") in ("item", "item-pages", "drain"):
609
624
  return run_queued_build(client, task, lambda_context)
610
625
  if task.get("task") == "all":
@@ -659,7 +674,7 @@ def set_story_step_action(arguments: dict, event: dict) -> dict:
659
674
  return {"ok": False, "errors": [{"code": "not-signed-in", "message": "Sign in as an editor to change a checklist step.", "line": None}]}
660
675
  agent = (arguments.get("agent") or "").strip()
661
676
  label = agent or (arguments.get("actorLabel") or "").strip() or (event.get("identity") or {}).get("username") or "editor"
662
- client, _claims = create_authoring_client()
677
+ client = authoring_client()
663
678
  actor = {"kind": ACTOR_AGENT if agent else ACTOR_PERSON, "label": label, "sub": person}
664
679
  try:
665
680
  if not arguments.get("state"): # no state: a note on the step, whatever its state, changing nothing else
@@ -675,7 +690,11 @@ def set_story_step_action(arguments: dict, event: dict) -> dict:
675
690
 
676
691
 
677
692
  def save_item_draft_action(arguments: dict, actor: str, approved_by: str | None = None) -> dict:
678
- client, _claims = create_authoring_client()
693
+ client = authoring_client()
694
+ if arguments.get("id") and current_tenant_context().mode == "shared" and client.get_record("Item", arguments["id"]) is None:
695
+ # A shared stack's editor names a story it can see: an id that is not the tenant's answers "not found" and writes nothing
696
+ # (a missing row and another tenant's row are indistinguishable to a tenant client, and neither is created here).
697
+ raise PublishError("not-found", "That story was not found.")
679
698
  if arguments.get("newVersion") and arguments.get("id"):
680
699
  existing = client.get_record("Item", arguments["id"])
681
700
  if existing is None:
@@ -780,7 +799,7 @@ def projection_status_action(arguments: dict) -> dict:
780
799
  jobs = publish_jobs_from_environment()
781
800
  if jobs is None:
782
801
  return {"ok": True, "projection": {"state": "unknown", "reason": "this site keeps no build records (no projection lock table)"}}
783
- client, _claims = create_authoring_client()
802
+ client = authoring_client()
784
803
  candidate = client.get_record("Item", arguments["id"]) or {}
785
804
  job = jobs.status(arguments["id"])
786
805
  answer = job_answer(job)
@@ -822,7 +841,7 @@ def start_projection_job(client, item_id: str, *, version: int | None, published
822
841
  def publish_item_action(arguments: dict, actor: str, approved_by: str | None = None) -> dict:
823
842
  if arguments.get("jobStatus"):
824
843
  return projection_status_action(arguments)
825
- client, _claims = create_authoring_client()
844
+ client = authoring_client()
826
845
  candidate = client.get_record("Item", arguments["id"]) or {}
827
846
  live = client.get_record("PublishedItem", published_item_id_for(candidate.get("lineageId") or arguments["id"]))
828
847
  render_preflight(client, arguments["id"]) # a page the site cannot render is refused before any published data is written
@@ -863,7 +882,7 @@ def remove_schedules(client, item: dict, version_number: int | None) -> dict:
863
882
 
864
883
 
865
884
  def unpublish_item_action(arguments: dict, actor: str) -> dict:
866
- client, _claims = create_authoring_client()
885
+ client = authoring_client()
867
886
  candidate = client.get_record("Item", arguments["id"]) or {}
868
887
  result = unpublish_item(client, arguments["id"], actor=actor)
869
888
  response = {"ok": True, "changed": result.changed}
@@ -888,7 +907,7 @@ def caller_from_event(event: dict) -> Caller:
888
907
 
889
908
  def schedule_item_action(arguments: dict, event: dict) -> dict:
890
909
  """``scheduleItem`` ``{"operation": "schedule" | "schedule_list", "arguments": {...}}``: the one operation table of scheduled publishing (story_schedule.OPERATIONS)."""
891
- client, _claims = create_authoring_client()
910
+ client = authoring_client()
892
911
  try:
893
912
  service = schedule_service(client)
894
913
  except ScheduleError as error:
@@ -915,7 +934,7 @@ def publish_scheduled_action(client, task: dict) -> dict:
915
934
  def move_story_stage_action(arguments: dict, actor: str) -> dict:
916
935
  from papyrus_content.story_reporting import move_story_stage
917
936
 
918
- client, _claims = create_authoring_client()
937
+ client = authoring_client()
919
938
  try:
920
939
  result = move_story_stage(client, arguments["lineageId"], arguments["stage"], actor=actor, reason=arguments.get("reason"))
921
940
  except ValueError as error:
@@ -936,7 +955,7 @@ def suggest_reference_links_action(arguments: dict) -> dict:
936
955
  index_arn = (os.environ.get("PAPYRUS_S3_VECTOR_INDEX_ARN") or "").strip()
937
956
  if not index_arn:
938
957
  return {"ok": False, "errors": [{"code": "knowledge-index-not-configured", "message": "Suggestions need the knowledge index.", "line": None}]}
939
- client, _claims = create_authoring_client()
958
+ client = authoring_client()
940
959
  provider = S3VectorsProvider(vector_index_arn=index_arn, region_name=os.environ.get("AWS_REGION") or os.environ.get("AWS_DEFAULT_REGION"))
941
960
  try:
942
961
  return {"ok": True, **suggest_for(client, provider, reference_id)}
@@ -960,7 +979,7 @@ def add_story_agent_note_action(arguments: dict, person: str | None) -> dict:
960
979
 
961
980
  if not person:
962
981
  return {"ok": False, "errors": [{"code": "not-signed-in", "message": "Sign in as an editor to add an agent note.", "line": None}]}
963
- client, _claims = create_authoring_client()
982
+ client = authoring_client()
964
983
  try:
965
984
  version = arguments.get("versionNumber")
966
985
  result = save_agent_note(
@@ -978,7 +997,7 @@ def create_story_from_reference_action(arguments: dict, actor: str) -> dict:
978
997
  from papyrus_content.ideas.signal_queue import ReferenceSummaries
979
998
  from papyrus_content.story_from_reference import create_story_from_reference
980
999
 
981
- client, _claims = create_authoring_client()
1000
+ client = authoring_client()
982
1001
  summaries = ReferenceSummaries(client)
983
1002
  try:
984
1003
  result = create_story_from_reference(
@@ -1012,16 +1031,25 @@ def handler(event, context=None):
1012
1031
 
1013
1032
 
1014
1033
  def _handle(event, context=None):
1015
- if PROJECTION_TASK_KEY in event:
1016
- return run_projection_task(event[PROJECTION_TASK_KEY], context)
1034
+ if PROJECTION_TASK_KEY in event: # a task the platform invoked: on a shared stack it names its tenant, like any IAM-signed call
1035
+ task = event[PROJECTION_TASK_KEY]
1036
+ with acting_for(build_invocation_tenant_context(task.get("tenantId"))):
1037
+ return run_projection_task(task, context)
1017
1038
  if "refreshSitePages" in event: # a direct invocation by an operator's profile: the operator lane needs no CloudFront rights of its own
1018
- return refresh_site_pages_action(event["refreshSitePages"], str(event.get("who") or "operator"))
1039
+ request = event["refreshSitePages"]
1040
+ with acting_for(build_invocation_tenant_context(request.get("tenantId"))):
1041
+ return refresh_site_pages_action({key: value for key, value in request.items() if key != "tenantId"}, str(event.get("who") or "operator"))
1042
+ with acting_for(build_event_tenant_context(event)): # one context per call, from the event's identity; a shared stack refuses before any read
1043
+ return _handle_field(event)
1044
+
1045
+
1046
+ def _handle_field(event):
1019
1047
  field = event["fieldName"]
1020
- arguments = parse_input(event["arguments"]["input"])
1048
+ arguments = {key: value for key, value in parse_input(event["arguments"]["input"]).items() if key != "tenantId"} # the tenant is never taken from the body (an IAM caller's is in the context)
1021
1049
  actor = actor_from_event(event)
1022
1050
  try:
1023
1051
  if field == "intakePendingReferences":
1024
- client, _claims = create_authoring_client()
1052
+ client = authoring_client()
1025
1053
  try:
1026
1054
  created = intake_references(client, arguments, event.get("identity") or {})
1027
1055
  from papyrus_content.reference_prediction_queue import queue_after_intake
@@ -1029,7 +1057,7 @@ def _handle(event, context=None):
1029
1057
  except IntakeError as error:
1030
1058
  return {"ok": False, "errors": [{"code": "intake-rejected", "message": str(error)}]}
1031
1059
  if field == "intakeEmailSubmissionReferences":
1032
- client, _claims = create_authoring_client()
1060
+ client = authoring_client()
1033
1061
  try:
1034
1062
  from papyrus_content.monitoring_view import default_email_store_factory
1035
1063
  receipt_store = default_email_store_factory(os.environ)()
@@ -1040,7 +1068,7 @@ def _handle(event, context=None):
1040
1068
  if field == "correctReferenceCapture":
1041
1069
  from papyrus_content.reference_curation_store import CurationError, correct_reference_capture
1042
1070
 
1043
- client, _claims = create_authoring_client()
1071
+ client = authoring_client()
1044
1072
  try:
1045
1073
  return correct_reference_capture(client, arguments, event.get("identity") or {})
1046
1074
  except CurationError as error:
@@ -16,6 +16,10 @@ let siteFilesForNextContentActionsBundle;
16
16
  export function setSiteFilesForContentActionsBundle(siteFiles) {
17
17
  siteFilesForNextContentActionsBundle = siteFiles;
18
18
  }
19
+ /** The site files the next content-actions bundle will hold (undefined: the bundle takes none). Read by the synth harness. */
20
+ export function siteFilesForContentActionsBundle() {
21
+ return siteFilesForNextContentActionsBundle;
22
+ }
19
23
  export const contentActions = defineFunction((scope) => {
20
24
  return new Function(scope, "papyrus-content-actions", {
21
25
  runtime: Runtime.PYTHON_3_12,
@@ -26,6 +26,11 @@ export function setSiteFilesForContentActionsBundle(siteFiles: SiteBundleFile[]
26
26
  siteFilesForNextContentActionsBundle = siteFiles;
27
27
  }
28
28
 
29
+ /** The site files the next content-actions bundle will hold (undefined: the bundle takes none). Read by the synth harness. */
30
+ export function siteFilesForContentActionsBundle(): SiteBundleFile[] | undefined {
31
+ return siteFilesForNextContentActionsBundle;
32
+ }
33
+
29
34
  export const contentActions = defineFunction(
30
35
  (scope: Construct) => {
31
36
  return new Function(scope, "papyrus-content-actions", {
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
  from typing import Any
6
6
 
7
7
  from papyrus_content.editorial_checks import GraphQLEditorialStore, Services, event_field_name, handle, load_provider_keys
8
+ from papyrus_content.tenant_context import acting_for, build_event_tenant_context
8
9
  from papyrus_cost_usage import SiteUsage
9
10
 
10
11
  # Amplify passes secrets to Python functions as placeholders; resolve them once per cold start.
@@ -15,7 +16,10 @@ USAGE = SiteUsage.from_environment()
15
16
 
16
17
  def handler(event: dict[str, Any], _context: Any = None) -> dict[str, Any]:
17
18
  try:
18
- return handle(event_field_name(event), event.get("arguments") or {}, Services(store=GraphQLEditorialStore(), usage=USAGE))
19
+ context = build_event_tenant_context(event) # one context per call; a shared stack refuses before any read
20
+ with acting_for(context):
21
+ store = GraphQLEditorialStore(tenant_id=context.tenant_id)
22
+ return handle(event_field_name(event), event.get("arguments") or {}, Services(store=store, usage=USAGE))
19
23
  finally:
20
24
  # A frozen Lambda loses what is only in memory: send before the invocation returns. Never raises.
21
25
  USAGE.flush()
@@ -1,6 +1,7 @@
1
1
  import { secret } from "@aws-amplify/backend";
2
2
  import { Stack } from "aws-cdk-lib";
3
3
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
4
+ import { connectToSiteApi } from "../../site-api-access.js";
4
5
  /** The model operations the function performs with its own role. The two context reads are its least-privilege access to private policy. */
5
6
  export const EDITORIAL_CHECKS_FUNCTION_FIELDS = [
6
7
  "Query/fields/listKnowledgeCorporaByRoleAndName",
@@ -40,7 +41,7 @@ export function editorialChecksSecretParameters(region, account, appId) {
40
41
  export function wireEditorialChecks(backend) {
41
42
  const lambda = backend.editorialChecks.resources.lambda;
42
43
  const stack = Stack.of(lambda);
43
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
44
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
44
45
  for (const name of EDITORIAL_CHECKS_SECRETS)
45
46
  backend.editorialChecks.addEnvironment(name, secret(name));
46
47
  lambda.addToRolePolicy(new PolicyStatement({
@@ -2,6 +2,7 @@ import { secret } from "@aws-amplify/backend";
2
2
  import { Stack } from "aws-cdk-lib";
3
3
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
4
4
  import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
5
+ import { connectToSiteApi } from "../../site-api-access";
5
6
 
6
7
  /** The model operations the function performs with its own role. The two context reads are its least-privilege access to private policy. */
7
8
  export const EDITORIAL_CHECKS_FUNCTION_FIELDS = [
@@ -45,7 +46,7 @@ export function editorialChecksSecretParameters(region: string, account: string,
45
46
  export function wireEditorialChecks(backend: any): void {
46
47
  const lambda = backend.editorialChecks.resources.lambda as LambdaFunction;
47
48
  const stack = Stack.of(lambda);
48
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
49
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
49
50
  for (const name of EDITORIAL_CHECKS_SECRETS) backend.editorialChecks.addEnvironment(name, secret(name));
50
51
  lambda.addToRolePolicy(
51
52
  new PolicyStatement({
@@ -1,4 +1,5 @@
1
1
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
2
+ import { connectToSiteApi } from "../../site-api-access.js";
2
3
  /**
3
4
  * What the function reads and writes with its own role, through the site's own API (`allow.resource(imageService)` in the schema grants query and
4
5
  * mutate; the function calls no other service). Today: the doctrine and Story `Item` records it reads by index and the new profile version it writes,
@@ -25,7 +26,7 @@ export const IMAGE_SERVICE_BUCKET_ACTIONS = ["s3:GetObject", "s3:PutObject"];
25
26
  /** The function's environment: the site's own API. It holds no secret and calls no provider in this step. */
26
27
  export function wireImageService(backend) {
27
28
  const lambda = backend.imageService.resources.lambda;
28
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
29
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
29
30
  // Read and write of the guideline documents, on the payload prefix of Item versions only (the role, not a bucket policy, as the other functions do it,
30
31
  // so the storage and data stacks do not depend on each other).
31
32
  const bucket = backend.storage.resources.bucket;
@@ -1,5 +1,6 @@
1
1
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
2
2
  import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
3
+ import { connectToSiteApi } from "../../site-api-access";
3
4
 
4
5
  /**
5
6
  * What the function reads and writes with its own role, through the site's own API (`allow.resource(imageService)` in the schema grants query and
@@ -29,7 +30,7 @@ export const IMAGE_SERVICE_BUCKET_ACTIONS = ["s3:GetObject", "s3:PutObject"];
29
30
  /** The function's environment: the site's own API. It holds no secret and calls no provider in this step. */
30
31
  export function wireImageService(backend: any): void {
31
32
  const lambda = backend.imageService.resources.lambda as LambdaFunction;
32
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
34
  // Read and write of the guideline documents, on the payload prefix of Item versions only (the role, not a bucket policy, as the other functions do it,
34
35
  // so the storage and data stacks do not depend on each other).
35
36
  const bucket = backend.storage.resources.bucket;
@@ -1,5 +1,6 @@
1
1
  import { Stack } from "aws-cdk-lib";
2
2
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
3
+ import { connectToSiteApi } from "../../site-api-access.js";
3
4
  /** The monitoring stack writes the table's name here (infra/monitoring/papyrus-monitoring.yaml). */
4
5
  export const MONITORING_TABLE_PARAMETER = "/papyrus/monitoring/table-name";
5
6
  /** Reads only: a single item or a key-range query. No Scan, no writes, no other table. */
@@ -23,7 +24,7 @@ export function wireMonitoringView(backend, emailMonitorId = "hn") {
23
24
  const lambda = backend.monitoringView.resources.lambda;
24
25
  const stack = Stack.of(lambda);
25
26
  lambda.addEnvironment("PAPYRUS_USER_POOL_ISSUER", `https://cognito-idp.${stack.region}.amazonaws.com/${backend.auth.resources.userPool.userPoolId}`);
26
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
27
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl);
27
28
  lambda.addEnvironment("PAPYRUS_MONITORING_TABLE_PARAMETER", MONITORING_TABLE_PARAMETER);
28
29
  lambda.addEnvironment("PAPYRUS_EMAIL_MONITOR_ID", emailMonitorId);
29
30
  lambda.addToRolePolicy(new PolicyStatement({
@@ -1,6 +1,7 @@
1
1
  import { Stack } from "aws-cdk-lib";
2
2
  import { Effect, PolicyStatement } from "aws-cdk-lib/aws-iam";
3
3
  import type { Function as LambdaFunction } from "aws-cdk-lib/aws-lambda";
4
+ import { connectToSiteApi } from "../../site-api-access";
4
5
 
5
6
  /** The monitoring stack writes the table's name here (infra/monitoring/papyrus-monitoring.yaml). */
6
7
  export const MONITORING_TABLE_PARAMETER = "/papyrus/monitoring/table-name";
@@ -29,7 +30,7 @@ export function wireMonitoringView(backend: any, emailMonitorId = "hn"): void {
29
30
  const lambda = backend.monitoringView.resources.lambda as LambdaFunction;
30
31
  const stack = Stack.of(lambda);
31
32
  lambda.addEnvironment("PAPYRUS_USER_POOL_ISSUER", `https://cognito-idp.${stack.region}.amazonaws.com/${backend.auth.resources.userPool.userPoolId}`);
32
- lambda.addEnvironment("PAPYRUS_GRAPHQL_ENDPOINT", backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
+ connectToSiteApi(lambda, backend.data.resources.cfnResources.cfnGraphqlApi.attrGraphQlUrl as string);
33
34
  lambda.addEnvironment("PAPYRUS_MONITORING_TABLE_PARAMETER", MONITORING_TABLE_PARAMETER);
34
35
  lambda.addEnvironment("PAPYRUS_EMAIL_MONITOR_ID", emailMonitorId);
35
36
  lambda.addToRolePolicy(
@@ -2,12 +2,13 @@ import { getAmplifyDataClientConfig } from "@aws-amplify/backend/function/runtim
2
2
  import { Amplify } from "aws-amplify";
3
3
  import { generateClient } from "aws-amplify/data";
4
4
  import type { Schema } from "../../data/resource";
5
+ import { actingFor, buildEventTenantContext, currentTenantContext } from "../shared/tenant-context";
6
+ import { newsroomSummaryPayloadId, tenantScopedClient } from "../shared/tenant-scoped-client";
5
7
  import { putJsonModelPayload, readJsonModelPayload } from "../shared/model-payloads";
6
8
 
7
9
  type DataClient = ReturnType<typeof generateClient<Schema>>;
8
10
  type DataClientErrors = Array<{ message?: string | null } | string | null> | null | undefined;
9
11
 
10
- const NEWSROOM_SUMMARY_PAYLOAD_ID = "knowledge-raw-payload-newsroom-summary-current";
11
12
  const NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND = "knowledgeRawPayload";
12
13
  const SUMMARY_STALE_AFTER_MS = 15 * 60 * 1000;
13
14
  let clientPromise: Promise<DataClient> | null = null;
@@ -15,16 +16,19 @@ let clientPromise: Promise<DataClient> | null = null;
15
16
  export const handler = async (
16
17
  event: Parameters<Schema["getNewsroomSummary"]["functionHandler"]>[0] | Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0],
17
18
  ) => {
18
- const fieldName = typeof event.info?.fieldName === "string" ? event.info.fieldName : "getNewsroomSummary";
19
- if (fieldName === "updateNewsroomSummary" || "delta" in event.arguments) {
20
- return updateNewsroomSummary(event as Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0]);
21
- }
22
- return getNewsroomSummary();
19
+ const context = buildEventTenantContext(event); // one context per call; a shared stack refuses before any read
20
+ return actingFor(context, () => {
21
+ const fieldName = typeof event.info?.fieldName === "string" ? event.info.fieldName : "getNewsroomSummary";
22
+ if (fieldName === "updateNewsroomSummary" || "delta" in event.arguments) {
23
+ return updateNewsroomSummary(event as Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0]);
24
+ }
25
+ return getNewsroomSummary();
26
+ });
23
27
  };
24
28
 
25
29
  async function getNewsroomSummary() {
26
30
  const client = await getDataClient();
27
- const response = await client.models.KnowledgeRawPayload.get({ id: NEWSROOM_SUMMARY_PAYLOAD_ID });
31
+ const response = await client.models.KnowledgeRawPayload.get({ id: newsroomSummaryPayloadId(currentTenantContext()) });
28
32
  assertNoDataErrors(response.errors, "get Newsroom summary snapshot");
29
33
  const payload = await readNewsroomSummaryPayload(client);
30
34
  return summaryFromPayload(normalizeSummaryPayload(payload, response.data?.updatedAt ?? new Date().toISOString()));
@@ -33,7 +37,7 @@ async function getNewsroomSummary() {
33
37
  async function updateNewsroomSummary(event: Parameters<Schema["updateNewsroomSummary"]["functionHandler"]>[0]) {
34
38
  const client = await getDataClient();
35
39
  const now = new Date().toISOString();
36
- const response = await client.models.KnowledgeRawPayload.get({ id: NEWSROOM_SUMMARY_PAYLOAD_ID });
40
+ const response = await client.models.KnowledgeRawPayload.get({ id: newsroomSummaryPayloadId(currentTenantContext()) });
37
41
  assertNoDataErrors(response.errors, "get Newsroom summary snapshot");
38
42
  const currentPayload = normalizeSummaryPayload(await readNewsroomSummaryPayload(client), now);
39
43
  const delta = parseJsonObject(event.arguments.delta);
@@ -54,7 +58,7 @@ async function getDataClient(): Promise<DataClient> {
54
58
  return generateClient<Schema>();
55
59
  })();
56
60
  }
57
- return clientPromise;
61
+ return tenantScopedClient(await clientPromise, currentTenantContext());
58
62
  }
59
63
 
60
64
  async function upsertNewsroomSummaryPayload(
@@ -64,7 +68,7 @@ async function upsertNewsroomSummaryPayload(
64
68
  now: string,
65
69
  ): Promise<void> {
66
70
  const input = {
67
- id: NEWSROOM_SUMMARY_PAYLOAD_ID,
71
+ id: newsroomSummaryPayloadId(currentTenantContext()),
68
72
  ownerType: "newsroom",
69
73
  ownerId: "newsroom",
70
74
  payloadKind: "summary-snapshot",
@@ -79,7 +83,7 @@ async function upsertNewsroomSummaryPayload(
79
83
  }
80
84
  await putJsonModelPayload(
81
85
  client as any,
82
- { ownerKind: NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND, ownerId: NEWSROOM_SUMMARY_PAYLOAD_ID, importRunId: input.importRunId },
86
+ { ownerKind: NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND, ownerId: newsroomSummaryPayloadId(currentTenantContext()), importRunId: input.importRunId },
83
87
  "raw_payload",
84
88
  "summary-snapshot",
85
89
  payload,
@@ -91,7 +95,7 @@ async function readNewsroomSummaryPayload(client: DataClient): Promise<Record<st
91
95
  return readJsonModelPayload(
92
96
  client as any,
93
97
  NEWSROOM_SUMMARY_PAYLOAD_OWNER_KIND,
94
- NEWSROOM_SUMMARY_PAYLOAD_ID,
98
+ newsroomSummaryPayloadId(currentTenantContext()),
95
99
  "raw_payload",
96
100
  "summary-snapshot",
97
101
  );