From b52db465789e0b16e5c0ad1c97d3228548536b1f Mon Sep 17 00:00:00 2001 From: "Scion Agent (art-9694-dev)" Date: Sat, 28 Nov 2026 01:16:44 +0000 Subject: [PATCH] fix(messaging): deliver single inbox attachment for artifact-backed messages Stop copying artifact-backed web chat attachments into the project scratchpad in project-topic and native project-group threads so that delivered messages list each attachment once at ~/.scion/inbox//, with no duplicate scratchpad path, no attachment_mounts entry, and no 'also visible to sibling agents' body note (ptone/scion#9694). - Skip ref.artifact entries in stageChatAttachments (also fixing the ON->OFF experiment toggle double-listing edge case) and drop its unused messageID parameter. - Remove stageArtifactAttachment, errNoAttachmentStaging, OpenBoundAttachment, applyProjection, AttachmentProjectedLine, and ProjectedPath/ProjectedMount fields from AttachmentRef, AttachmentDelivery, and AttachmentPlanEntry. - Drop the scratchpad fallback for old brokers lacking Capabilities.AttachmentDelivery (they still emit the 'Attachment not delivered' line; sibling agents can fetch via scion conversation get-message --save-attachments). - Keep legacy (!ref.artifact) scratchpad staging and attachment_mounts intact until ptone/scion#4602 retires AttachmentStore. - Update affected tests, experiment description, and docs. --- .../src/content/docs/hosted/user/messaging.md | 4 +- .../content/docs/reference/server-config.md | 2 +- pkg/artifacts/attachments.go | 33 +------ pkg/artifacts/attachments_test.go | 26 ----- pkg/experiments/registry.go | 2 +- pkg/hub/attachment_delivery.go | 11 --- pkg/hub/attachments.go | 6 -- pkg/hub/attachments_artifacts.go | 22 ----- pkg/hub/attachments_artifacts_reach_test.go | 38 +++----- pkg/hub/attachments_artifacts_test.go | 59 +++++------- pkg/hub/attachments_audience_test.go | 21 ++-- pkg/hub/attachments_nfs_test.go | 4 +- pkg/hub/attachments_p4_test.go | 54 ++--------- pkg/hub/attachments_refs_test.go | 13 +-- pkg/hub/attachments_send.go | 1 - pkg/hub/attachments_staging_test.go | 2 +- pkg/hub/capability_keyring_test.go | 21 ++-- ...andlers_broker_inbound_attachments_test.go | 3 - pkg/hub/handlers_chat_v2.go | 95 ++++++------------- pkg/messages/types.go | 12 --- pkg/messaging/render_delivery.go | 28 +----- .../render_delivery_projection_test.go | 85 +++++++++-------- 22 files changed, 150 insertions(+), 392 deletions(-) diff --git a/docs-site/src/content/docs/hosted/user/messaging.md b/docs-site/src/content/docs/hosted/user/messaging.md index 8abb5c7dfd4..f9f46c534de 100644 --- a/docs-site/src/content/docs/hosted/user/messaging.md +++ b/docs-site/src/content/docs/hosted/user/messaging.md @@ -75,7 +75,7 @@ With the `hub.attachment_artifacts` experiment on, a file uploaded in web chat o - **Group conversation without a project:** its current participants. Someone who joins can read the attachments of earlier messages, and someone who leaves stops being able to read them. - **Anyone the message is addressed to.** -When the message goes to an agent, the file is delivered into that agent's own home (see [Attachments for agents](#attachments-for-agents)). For a message in a project thread, whose readers are the whole project, a copy is also placed in the project's `scratchpad` shared directory at `.attachments/_webchat//`, so the project's other agents can find it (if looking up the topic fails, the Hub fails closed and skips the shared-directory copy rather than copying into the project scratchpad). Every agent and member with access to that directory can read the copy. Direct messages and group conversations are delivered only into the recipients' homes, with no shared copy. Copies are removed after `messaging.attachment_inbox_retention_days` (7 days by default). The experiment is on by default wherever the artifact service is ready, including Hubs with local storage (no object store needed), and on Hubs whose resource storage is an object store. +When the message goes to an agent, the file is delivered into that agent's own home (see [Attachments for agents](#attachments-for-agents)), with no copy placed in the project's `scratchpad` shared directory. Other agents that may read the message can fetch its attachments with `scion conversation get-message --save-attachments`. The experiment is on by default wherever the artifact service is ready, including Hubs with local storage (no object store needed), and on Hubs whose resource storage is an object store. Until it is sent, only the uploader can read it, and an upload that is not sent within 24 hours is removed. Deleting a message makes its attachments unreadable at once, and their stored bytes are removed after the artifact garbage-collection grace period. Any user who cannot read it gets the same "not found" answer as for an attachment that does not exist. A user access token uploads, sends and reads them for its holder under its own rule: it needs `inbox:read` to read and `inbox:write` to upload and send. It reads an attachment only when its holder may read the message, and the token's boundary must reach the project recorded for the attachment: a project boundary for that project, or a hub boundary. An attachment with no project, and the holder's own upload before it is sent, need a hub boundary. In a direct message with an agent, the token also needs `agent:read` on every agent in the conversation. An attachment recorded before projects were recorded is not readable with a token. Attachments are read only through their message: they have no share links, grants or versions, and they are not listed among artifacts. @@ -89,7 +89,7 @@ Each file can be up to the artifact file size limit (`artifacts.max_file_bytes`, With the `hub.attachment_artifacts` experiment on, agents send and receive attachments as files: - **Sending:** `scion message --attach ` first asks the Hub where uploads go. When the Hub stores attachments as artifacts (which for an agent caller also requires `project:artifact:read` on its token), the CLI checks the files, uploads them and names them in the send. Each file must be a readable regular file, no two files may have the same name, and HTML and SVG files are refused: publish one with `scion artifact publish` and send it with `--artifact`. With an agent recipient, the files must fit the delivery limit below. Any path works; the files do not need to be in a shared directory. A group send uploads the files once per recipient. If any file fails to upload, nothing is sent. When the experiment is off, or when the calling agent's token lacks `project:artifact:read` (for example when its delegation-chain ceiling withheld it, in which case `GET /api/v1/chat/attachments` answers `"legacy"` and `POST /api/v1/chat/attachments` answers `404 attachment_artifacts_unavailable`), `--attach` stages files in the shared directory as before. -- **Receiving:** an agent that may read the message gets each file at `~/.scion/inbox//` before the message text arrives, and the message lists those paths. For a project thread the message also lists the file's copy in the project scratchpad, after the inbox path, tagged with its shared directory (`attachment_mounts` in the envelope) and described as also visible to sibling agents; use the inbox path. `` is the file name with every character other than letters, digits, `.`, `_` and `-` replaced by `_`. A file that could not be delivered gets one line after the message text: `Attachment not delivered: (): . Ask the sender to resend it.` +- **Receiving:** an agent that may read the message gets each file at `~/.scion/inbox//` before the message text arrives, and the message lists each attachment once at that path. `` is the file name with every character other than letters, digits, `.`, `_` and `-` replaced by `_`. A file that could not be delivered gets one line after the message text: `Attachment not delivered: (): . Ask the sender to resend it.` Other agents that may read the message can fetch its attachments with `scion conversation get-message --save-attachments`. - **Which agents get a file:** the agents that may read the message: a participant of its conversation, an agent of the project for a project thread, and an agent the message is addressed to, including an agent @mentioned in it. An agent in another project that is the recipient gets the file; other agents of that project do not. - **A snapshot:** a delivered file stays in the agent's home after the message is deleted, until the agent's inbox is pruned (directories older than `messaging.attachment_inbox_retention_days`, 7 days by default) or the agent is deleted. - **Kubernetes default pods:** the agent's home lives in the pod, so delivered files are lost when the pod is recreated. Homes on NFS, and runtimes that keep the home on the host, keep them. diff --git a/docs-site/src/content/docs/reference/server-config.md b/docs-site/src/content/docs/reference/server-config.md index 874d39900d9..e45e7b85ddd 100644 --- a/docs-site/src/content/docs/reference/server-config.md +++ b/docs-site/src/content/docs/reference/server-config.md @@ -1151,7 +1151,7 @@ With the `nfs` backend, the Hub and brokers also apply the following: - **Symlink-safe access**: Every Hub operation on an NFS shared directory goes through the same confined resolver. This covers the web file browser, archive downloads, and shared-dir deletion. The resolver walks each path component with `O_NOFOLLOW`, anchored on the inode of the project's tree, and refuses any symlink in the path. A missing or incomplete `nfs` block, or an unusable host base directory, fails closed on the Hub as well as on agent start. - **Leaf modes and ACLs**: A newly created shared directory gets mode `2775` (setgid, group-writable) and a minimal default POSIX ACL, so files agents create inside it inherit group write access regardless of umask. If the export does not support POSIX ACLs, a warning is logged once and the directory stays plain `2775` with no ACL. Files created inside such a directory follow each writer's umask (usually `022`), so they are not group-writable. Directories that already existed are never modified. See the [hybrid tier guide](https://github.com/GoogleCloudPlatform/scion/blob/main/docs/deploy/hybrid-tier.md) for the manual fix-up recipe. -- **Chat attachments**: Attachments are delivered into each recipient agent's inbox (`~/.scion/inbox//`) when `hub.attachment_artifacts` is on. It is on by default wherever the artifact service is ready, including the workstation server and other Hubs with local storage (no object store is needed), and on Hubs whose resource storage is an object store; a stored override still applies. For a message in a project topic thread, whose readers are the whole project, the Hub also copies each attachment into the project's `scratchpad` shared directory at `.attachments/_webchat//`, and the message lists that inbox path first. It resolves the directory the same way as the file browser, so on NFS the copy lands where agents mount the scratchpad, and every write goes through the same confined resolver. The message tags the copy's container path with its shared directory (`attachment_mounts` in the delivered envelope). Attachments in direct conversations and participant-list group conversations are delivered only into the recipients' inboxes, with no shared copy, on every storage backend. An attachment that is not stored as an artifact (for example while `hub.attachment_artifacts` is turned off) has no inbox delivery. On shared storage (NFS) its scratchpad copy is likewise made only for project topic threads; a direct or group conversation's attachment is not copied there. On the workstation server (local storage) the copy is how an agent reads the file, so it is made for every message, direct conversations included. The other agents of the project can then read a direct message's attachment. This is a known limitation of that configuration, and it goes away once the Hub stores attachments as artifacts. Files an agent attaches with `scion message --attach` are read from the same directory. Scratchpad copies older than `messaging.attachment_inbox_retention_days` (default 7) are removed by the Hub's hourly maintenance pass, on every backend. +- **Chat attachments**: Attachments are delivered into each recipient agent's inbox (`~/.scion/inbox//`) when `hub.attachment_artifacts` is on, with no copy placed in the project's `scratchpad` shared directory on any conversation type or storage backend; sibling agents that may read the message can fetch its attachments with `scion conversation get-message --save-attachments`. The experiment is on by default wherever the artifact service is ready, including the workstation server and other Hubs with local storage (no object store is needed), and on Hubs whose resource storage is an object store; a stored override still applies. An attachment that is not stored as an artifact (for example while `hub.attachment_artifacts` is turned off) has no inbox delivery and is staged into the project's `scratchpad` shared directory at `.attachments/_webchat//`, tagged with its shared directory (`attachment_mounts` in the delivered envelope). On shared storage (NFS) that legacy scratchpad copy is made only for project topic threads, resolved through the same confined resolver as the file browser; a direct or group conversation's legacy attachment is not copied there. On the workstation server (local storage) the legacy copy is how an agent reads the file, so it is made for every message, direct conversations included. The other agents of the project can then read a direct message's legacy attachment. This is a known limitation of that configuration, and it goes away once the Hub stores attachments as artifacts. Legacy files an agent attaches with `scion message --attach` are read from the same directory. Scratchpad copies older than `messaging.attachment_inbox_retention_days` (default 7) are removed by the Hub's hourly maintenance pass, on every backend. - **Ownership on an export that does not squash ids**: the broker creates the project chain as its own user and never changes ownership. Upper directories get `2755` and the leaf `2775`, and each inherits the group of a setgid parent. Pods create nothing on this export; they mount the existing leaf by `subPath`. When agents with different uids share a directory, for example Docker agents and Kubernetes pods, give the share directory (`/`) a shared group with the setgid bit (for example `chgrp ` and `chmod 2775`) so every leaf inherits it. Scion then adds that group to each agent that mounts the leaf; see [Agent groups](#agent-groups-on-nfs-shared-directories). - **Existing upper directories**: the expected layout for an upper directory that already exists on the export is setgid, group `nfs.gid`, not writable by others, and owned by the broker user or `nfs.uid`. An existing upper directory that is group- or other-writable or owned by another user, and does not have that layout, is left as it is and logged once per process as a warning. - **Cleanup on delete**: Deleting a project removes its whole `/` tree from the export (see [cleanup on project delete](#cleanup-on-project-delete)). Removing a single shared directory declaration deletes that directory. Both are best-effort: failures are logged and never block or roll back the database change. diff --git a/pkg/artifacts/attachments.go b/pkg/artifacts/attachments.go index 083b2f6ae93..9055b0e961e 100644 --- a/pkg/artifacts/attachments.go +++ b/pkg/artifacts/attachments.go @@ -384,37 +384,6 @@ func (s *Service) MayReadAttachments(ctx context.Context, messageID string, mess return mh.MayReadMessage(ctx, messageID, messageProjectID) } -// OpenBoundAttachment opens the bytes of attachment artifactID, which must -// be bound to message messageID, for the host to deliver to the message's -// addressees. It checks no caller: the host calls it only from its own -// send path, after the send was authorized and the message stored, never -// on behalf of a request that names an attachment. -func (s *Service) OpenBoundAttachment(ctx context.Context, artifactID, messageID string) (io.ReadCloser, AttachmentInfo, error) { - b, ok := s.backend() - if !ok { - return nil, AttachmentInfo{}, ErrUnavailable - } - if !canonicalID(artifactID) || messageID == "" { - return nil, AttachmentInfo{}, ErrNotFound - } - a, err := b.store.GetAttachment(ctx, artifactID) - if err != nil { - return nil, AttachmentInfo{}, err - } - if a.ID != artifactID || a.ScopeKind != ScopeKindMessage || a.ScopeRef != messageID { - return nil, AttachmentInfo{}, ErrNotFound - } - f, err := attachmentFile(ctx, b, a) - if err != nil { - return nil, AttachmentInfo{}, err - } - rc, _, err := b.blobs.Download(ctx, BlobPath(b.hubID, f.SHA256)) - if err != nil { - return nil, AttachmentInfo{}, fmt.Errorf("artifacts: open attachment: %w", err) - } - return rc, AttachmentInfo{ID: a.ID, Name: f.Path, MediaType: f.MediaType, Size: f.Size}, nil -} - // DeliveryRedirectTTL is the lifetime of the object-store URL a broker is // redirected to when it redeems an attachment delivery capability // (ptone/scion#4596). @@ -422,7 +391,7 @@ const DeliveryRedirectTTL = 60 * time.Second // ServeBoundAttachment answers a broker redeeming a delivery capability // for attachment artifactID, which must be bound to message messageID -// (ptone/scion#4596). Like OpenBoundAttachment it checks no caller: the host +// (ptone/scion#4596). It checks no caller: the host // calls it only from its capability redemption route, after the capability // (issued under the read decision for the recipient) has been verified and // spent. The local provider streams the bytes; an object store answers a diff --git a/pkg/artifacts/attachments_test.go b/pkg/artifacts/attachments_test.go index fb2615eda00..96911e45f7c 100644 --- a/pkg/artifacts/attachments_test.go +++ b/pkg/artifacts/attachments_test.go @@ -23,7 +23,6 @@ import ( "encoding/json" "errors" "fmt" - "io" "net/http" "net/http/httptest" "strings" @@ -469,31 +468,6 @@ func TestCreateAttachmentLimits(t *testing.T) { } } -// TestOpenBoundAttachment: the delivery opener reads only an attachment -// bound to the named message. -func TestOpenBoundAttachment(t *testing.T) { - f := newAttachmentFixture(t, false) - ctx := context.Background() - sent := f.send(userU, "msg-1", pngBytes) - up := f.upload(userU, "a.txt", "text/plain", []byte("x")) - - rc, info, err := f.svc.OpenBoundAttachment(ctx, sent, "msg-1") - if err != nil { - t.Fatalf("bound attachment: %v", err) - } - b, _ := io.ReadAll(rc) - _ = rc.Close() - if !bytes.Equal(b, pngBytes) || info.Name != "shot.png" { - t.Errorf("read %q, info %+v", b, info) - } - if _, _, err := f.svc.OpenBoundAttachment(ctx, sent, "msg-2"); !errors.Is(err, ErrNotFound) { - t.Errorf("other message = %v, want ErrNotFound", err) - } - if _, _, err := f.svc.OpenBoundAttachment(ctx, up, "msg-1"); !errors.Is(err, ErrNotFound) { - t.Errorf("unsent upload = %v, want ErrNotFound", err) - } -} - // TestMessageAttachmentsAndRetireScope: history lists a message's // attachments until the message is retired. func TestMessageAttachmentsAndRetireScope(t *testing.T) { diff --git a/pkg/experiments/registry.go b/pkg/experiments/registry.go index 7bc2a5fbae5..97569d903f8 100644 --- a/pkg/experiments/registry.go +++ b/pkg/experiments/registry.go @@ -1056,7 +1056,7 @@ var compiled = []Experiment{ { Name: AttachmentArtifacts, Title: "Attachments as artifacts", - Description: "Stores files uploaded in web chat in the artifact service as attachments of the message they are sent in: the stored file is readable exactly by the readers of that message, and is removed when the message is deleted. It is delivered into each recipient agent's inbox; for a message in a project topic thread a copy is also placed in the project's scratchpad shared directory, where every agent and member with access to that directory can read it (direct and group conversations get inbox delivery only). Gates the hub's attachment upload path (LayerServer; it also needs the artifact service with its settings section enabled, but not hub.artifacts) and is reserved for the web surfaces that follow (LayerWeb). Attachments stored while it was on stay readable after it is turned off. Defaults on wherever the artifact service is ready, local blob storage included, and on hubs whose resource storage is an object store (GCS).", + Description: "Stores files uploaded in web chat in the artifact service as attachments of the message they are sent in: the stored file is readable exactly by the readers of that message, and is removed when the message is deleted. It is delivered into each recipient agent's inbox (~/.scion/inbox//), with no copy in the project's scratchpad shared directory; sibling agents that may read the message can fetch it with `scion conversation get-message --save-attachments`. Gates the hub's attachment upload path (LayerServer; it also needs the artifact service with its settings section enabled, but not hub.artifacts) and is reserved for the web surfaces that follow (LayerWeb). Attachments stored while it was on stay readable after it is turned off. Defaults on wherever the artifact service is ready, local blob storage included, and on hubs whose resource storage is an object store (GCS).", Default: false, Layers: []Layer{LayerWeb, LayerServer}, Stage: StageAlpha, diff --git a/pkg/hub/attachment_delivery.go b/pkg/hub/attachment_delivery.go index 3129ab6ec48..aebf358a7be 100644 --- a/pkg/hub/attachment_delivery.go +++ b/pkg/hub/attachment_delivery.go @@ -359,22 +359,11 @@ func (d *attachmentDelivery) Plan(ctx context.Context, recipient *store.Agent, d e.State = messages.AttachmentDeliverable e.InboxPath = attachmentInboxPath(del.MessageID, name) } - applyProjection(&e) plan = append(plan, e) } return plan } -// applyProjection copies the delivery's scratchpad projection -// (ptone/scion#5830) onto plan entry e, which the envelope lists after the -// inbox path; a withheld recipient is told nothing about the attachment. -func applyProjection(e *messages.AttachmentPlanEntry) { - if e.State == messages.AttachmentWithheld { - return - } - e.ProjectedPath, e.ProjectedMount = e.Delivery.ProjectedPath, e.Delivery.ProjectedMount -} - // Issue returns the wire attachments of plan for one dispatch attempt to // recipient on broker brokerID: one fresh capability per deliverable entry, // after asking the recipient decision again. An entry whose decision diff --git a/pkg/hub/attachments.go b/pkg/hub/attachments.go index a80a90d9bfc..c2cad0fb74b 100644 --- a/pkg/hub/attachments.go +++ b/pkg/hub/attachments.go @@ -50,12 +50,6 @@ type AttachmentRef struct { // artifact by newArtifactAttachmentRef, for delivery into an agent's // home. Never serialized. sha256 string - // projectedPath and projectedMount are the container path and shared - // dir of an artifact attachment's projection into the project's - // scratchpad (ptone/scion#5827), set by stageChatAttachments on - // the send path and carried into AttachmentDelivery. Never serialized. - projectedPath string - projectedMount string } // AttachmentStore abstracts file storage for chat attachments. diff --git a/pkg/hub/attachments_artifacts.go b/pkg/hub/attachments_artifacts.go index b6bdfbaeee3..78d70e6bf6d 100644 --- a/pkg/hub/attachments_artifacts.go +++ b/pkg/hub/attachments_artifacts.go @@ -18,7 +18,6 @@ import ( "context" "errors" "fmt" - "io" "strings" "github.com/GoogleCloudPlatform/scion/pkg/artifacts" @@ -215,27 +214,6 @@ func legacyAttachmentRefs(refs []AttachmentRef) []AttachmentRef { return out } -// stageArtifactAttachment copies artifact attachment ref, bound to message -// messageID, into the agent staging directory and returns the agent-visible -// path. It is part of the send path only (stageChatAttachments), after the -// send was authorized and the message stored: the bytes are opened through -// OpenBoundAttachment, which checks no caller, so it must never be reached -// from a request that names an attachment. -func (s *Server) stageArtifactAttachment(ctx context.Context, staging *attachmentStaging, messageID string, ref AttachmentRef) (string, error) { - if staging == nil { - return "", errNoAttachmentStaging - } - svc := s.attachmentService() - return staging.stageFrom(func() (io.ReadCloser, error) { - rc, _, err := svc.OpenBoundAttachment(ctx, ref.ID, messageID) - return rc, err - }, ref.ID, ref.Name) -} - -// errNoAttachmentStaging: the project has no staging directory, and an -// artifact attachment has no hub-local path to send instead. -var errNoAttachmentStaging = errors.New("no attachment staging directory for this project") - // mergeArtifactAttachments adds the artifact attachments of the messages // in msgIDs to byMessage (the AttachmentStore attachments of history), // creating it when needed. One batched query finds the attachments of the diff --git a/pkg/hub/attachments_artifacts_reach_test.go b/pkg/hub/attachments_artifacts_reach_test.go index 6364e046695..878c1930299 100644 --- a/pkg/hub/attachments_artifacts_reach_test.go +++ b/pkg/hub/attachments_artifacts_reach_test.go @@ -25,26 +25,17 @@ import ( "testing" ) -// TestOpenBoundAttachmentReachableOnlyFromSendPath pins that the artifact -// service's OpenBoundAttachment, which reads an attachment's bytes without -// checking any caller, is reached from exactly one place in the hub: the -// send path, after the send is authorized and the message stored. The call -// chain must be -// -// sendAgentRouted -> stageChatAttachments -> stageArtifactAttachment -> OpenBoundAttachment -// -// and nothing else in the package (and its guardScanSubdirs subpackages) -// (no handler, no route) may call any link -// of it; nor may any other package of the module reference the opener. A -// new caller fails this test and needs a security review. -func TestOpenBoundAttachmentReachableOnlyFromSendPath(t *testing.T) { +// TestStageChatAttachmentsReachableOnlyFromSendPath pins that legacy +// attachment staging (stageChatAttachments) is reached only from +// sendAgentRouted, and that no caller-less OpenBoundAttachment opener +// exists in the module (ptone/scion#9694). +func TestStageChatAttachmentsReachableOnlyFromSendPath(t *testing.T) { // pkgmove:scan-covers guardScanSubdirs - // callersInPackage and valueUsesInPackage read pkg/hub and every guardScanSubdirs entry through readGuardScanDirs (nonTestGoFiles); guards the OpenBoundAttachment call chain. + // callersInPackage and valueUsesInPackage read pkg/hub and every guardScanSubdirs entry through readGuardScanDirs (nonTestGoFiles); guards the stageChatAttachments call chain. callers := callersInPackage(t, ".") want := map[string][]string{ - "OpenBoundAttachment": {"stageArtifactAttachment"}, - "stageArtifactAttachment": {"stageChatAttachments"}, - "stageChatAttachments": {"sendAgentRouted"}, + "stageChatAttachments": {"sendAgentRouted"}, + "ServeBoundAttachment": {"handleAttachmentDelivery"}, } for callee, wantCallers := range want { got := callers[callee] @@ -52,20 +43,13 @@ func TestOpenBoundAttachmentReachableOnlyFromSendPath(t *testing.T) { t.Errorf("%s is called from %v; want only %v", callee, got, wantCallers) } } - // The functions of the chain, the opener included, are never used as - // values (a handler or method value made from one would escape the - // call check above). - for name, n := range valueUsesInPackage(t, ".", []string{"OpenBoundAttachment", "stageArtifactAttachment", "stageChatAttachments"}) { + for name, n := range valueUsesInPackage(t, ".", []string{"stageChatAttachments", "ServeBoundAttachment"}) { if n > 0 { t.Errorf("%s is used as a value %d times; it may only be called", name, n) } } - // The opener is an exported method of the artifact service, so the rest - // of the module is checked too: outside its own declaration, the only - // reference to it in non-test code is the call above. - refs := moduleSymbolReferences(t, "../..", "OpenBoundAttachment") - if want := []string{"pkg/hub/attachments_artifacts.go:stageArtifactAttachment"}; strings.Join(refs, ",") != strings.Join(want, ",") { - t.Errorf("OpenBoundAttachment is referenced at %v; want only %v", refs, want) + if refs := moduleSymbolReferences(t, "../..", "OpenBoundAttachment"); len(refs) != 0 { + t.Errorf("OpenBoundAttachment must not be referenced in non-test code, found %v", refs) } } diff --git a/pkg/hub/attachments_artifacts_test.go b/pkg/hub/attachments_artifacts_test.go index 1b1727900f4..7d4f8735618 100644 --- a/pkg/hub/attachments_artifacts_test.go +++ b/pkg/hub/attachments_artifacts_test.go @@ -496,11 +496,9 @@ func TestAttachmentArtifacts_ArtifactRoutesAnswerNotFound(t *testing.T) { } // While the experiment is on, an attachment stored as an artifact sent to -// an agent reaches it by delivery into its home (ptone/scion#4596), and is -// additionally projected into the project's scratchpad through the layout -// authority so sibling agents find it (ptone/scion#5827): the -// projection holds the stored bytes under .attachments/_webchat//. -func TestAttachmentArtifacts_ProjectedForSiblings(t *testing.T) { +// an agent reaches it by delivery into its home (ptone/scion#4596) only, +// with no scratchpad copy even in a project topic thread (ptone/scion#9694). +func TestAttachmentArtifacts_ProjectTopicNotCopiedToScratchpad(t *testing.T) { f := newRefFixture(t) enableAttachmentArtifacts(t, f) stagingDir := f.enableScratchpad(t) @@ -508,22 +506,18 @@ func TestAttachmentArtifacts_ProjectedForSiblings(t *testing.T) { id := f.uploadAs(t, f.ua, f.projA.ID, "log.txt", "agent bytes") f.sendWith(t, f.ua, f.topicA, id) - got, err := os.ReadFile(filepath.Join(stagingDir, id, "log.txt")) - require.NoError(t, err, "the attachment is projected into the scratchpad") - assert.Equal(t, "agent bytes", string(got)) + assert.NoDirExists(t, filepath.Join(stagingDir, id), "artifact attachments are not copied into the scratchpad") } -// stageChatAttachments records an artifact attachment's projection on its -// reference (experiment on, project topic thread) and adds no legacy entry -// for it; the delivery built from the reference carries the projection after -// the inbox path. On a direct conversation's key the same attachment is not -// projected. -func TestStageChatAttachments_ArtifactProjectionOnRef(t *testing.T) { +// stageChatAttachments skips artifact-backed attachment references on both +// direct conversations and project topic threads, adding no legacy staged +// paths or mounts and writing nothing to the scratchpad. +func TestStageChatAttachments_SkipsArtifactRefs(t *testing.T) { f := newRefFixture(t) enableAttachmentArtifacts(t, f) stagingDir := f.enableScratchpad(t) dm := dmKeyFor(t, "user", f.ua.ID, "user", f.uc.ID) - id := f.uploadAs(t, f.ua, f.projA.ID, "p.txt", "projected") + id := f.uploadAs(t, f.ua, f.projA.ID, "p.txt", "inbox-only") resp := f.sendWith(t, f.ua, dm, id) info, err := f.srv.attachmentService().MessageAttachments(context.Background(), []string{resp.ID}) @@ -532,25 +526,21 @@ func TestStageChatAttachments_ArtifactProjectionOnRef(t *testing.T) { // Direct conversation key: inbox only. refs := []AttachmentRef{newArtifactAttachmentRef(info[resp.ID][0])} - paths, mounts := f.srv.stageChatAttachments(context.Background(), dm, f.projA.ID, resp.ID, refs) + paths, mounts := f.srv.stageChatAttachments(context.Background(), dm, f.projA.ID, refs) assert.Empty(t, paths) assert.Empty(t, mounts) - assert.Empty(t, refs[0].projectedPath, "a DM attachment is never projected") assert.NoDirExists(t, filepath.Join(stagingDir, id)) - // Project topic thread key: projected. + // Project topic thread key: also inbox only. refs = []AttachmentRef{newArtifactAttachmentRef(info[resp.ID][0])} - paths, mounts = f.srv.stageChatAttachments(context.Background(), f.topicA, f.projA.ID, resp.ID, refs) + paths, mounts = f.srv.stageChatAttachments(context.Background(), f.topicA, f.projA.ID, refs) assert.Empty(t, paths, "a delivered artifact attachment adds no legacy entry") assert.Empty(t, mounts) - assert.Equal(t, "/scion-volumes/scratchpad/.attachments/_webchat/"+id+"/p.txt", refs[0].projectedPath) - assert.Equal(t, attachmentSharedDirName, refs[0].projectedMount) - assert.FileExists(t, filepath.Join(stagingDir, id, "p.txt")) + assert.NoDirExists(t, filepath.Join(stagingDir, id)) dels := attachmentDeliveries(resp.ID, refs) require.Len(t, dels, 1) - assert.Equal(t, refs[0].projectedPath, dels[0].ProjectedPath) - assert.Equal(t, attachmentSharedDirName, dels[0].ProjectedMount) + assert.Equal(t, id, dels[0].ArtifactID) } // TestAttachmentArtifacts_DMToAgentNotProjected: with artifacts on, an @@ -577,12 +567,12 @@ func TestAttachmentArtifacts_DMToAgentNotProjected(t *testing.T) { assert.Equal(t, "legacy bytes", string(got)) } -// TestAttachmentArtifacts_UploadedOnSentOffNotProjectedInDM: an attachment +// TestAttachmentArtifacts_UploadedOnSentOffNotProjected: an attachment // uploaded as an artifact while the experiment was on, and sent after it -// was turned off, is still delivered into the recipient's inbox, so in a -// direct conversation it gets no scratchpad copy either; in a project topic -// thread it is staged as before. -func TestAttachmentArtifacts_UploadedOnSentOffNotProjectedInDM(t *testing.T) { +// was turned off, is still delivered into the recipient's inbox only — +// neither a direct conversation nor a project topic thread gets a scratchpad +// copy (avoiding double-listing on ON->OFF transition, ptone/scion#9694). +func TestAttachmentArtifacts_UploadedOnSentOffNotProjected(t *testing.T) { f := newRefFixture(t) enableAttachmentArtifacts(t, f) stagingDir := f.enableScratchpad(t) @@ -608,12 +598,13 @@ func TestAttachmentArtifacts_UploadedOnSentOffNotProjectedInDM(t *testing.T) { require.Len(t, plan, 1) assert.NotEqual(t, messages.AttachmentWithheld, plan[0].State, "the recipient reads the attachment") assert.Equal(t, attachmentInboxPath(resp.ID, "dm.txt"), plan[0].InboxPath) - assert.Empty(t, plan[0].ProjectedPath) - f.sendWith(t, f.ua, f.topicA, inTopic) - got, err := os.ReadFile(filepath.Join(stagingDir, inTopic, "topic.txt")) - require.NoError(t, err, "a project topic thread still gets the copy") - assert.Equal(t, "topic bytes", string(got)) + topicResp := f.sendWith(t, f.ua, f.topicA, inTopic) + assert.NoDirExists(t, filepath.Join(stagingDir, inTopic), "an artifact attachment in a project topic thread gets no scratchpad copy even after experiment is toggled off") + topicInfo, err := f.srv.attachmentService().MessageAttachments(context.Background(), []string{topicResp.ID}) + require.NoError(t, err) + require.Len(t, topicInfo[topicResp.ID], 1, "the attachment is bound to the topic message") + assert.Equal(t, inTopic, topicInfo[topicResp.ID][0].ID) } // TestChatKeyReadAudience: the classification the send authorization, the diff --git a/pkg/hub/attachments_audience_test.go b/pkg/hub/attachments_audience_test.go index aaa6a18260a..60011dc73f4 100644 --- a/pkg/hub/attachments_audience_test.go +++ b/pkg/hub/attachments_audience_test.go @@ -72,10 +72,10 @@ func callTo(t *testing.T, disp *recordingDispatcher, a *store.Agent) dispatchCal } // TestAttachmentAudience_LocalDefaults_DMAndTopic: with the defaults on a -// local-storage hub (no object storage) a direct-conversation attachment to -// an agent is delivered to its inbox and never copied into the scratchpad; -// a project topic thread's attachment is delivered to the inbox and also -// projected. Both download from history. +// local-storage hub (no object storage) both direct-conversation and project +// topic thread artifact attachments are delivered to the recipient's inbox +// only, with no copy in the scratchpad and no attachment_mounts. Both download +// from history. func TestAttachmentAudience_LocalDefaults_DMAndTopic(t *testing.T) { f := newRefFixture(t) stagingDir, disp := localStorageHub(t, f) @@ -91,8 +91,8 @@ func TestAttachmentAudience_LocalDefaults_DMAndTopic(t *testing.T) { require.Len(t, call.StructuredMessage.AttachmentDeliveries, 1) del := call.StructuredMessage.AttachmentDeliveries[0] assert.Equal(t, resp.ID, del.MessageID) - assert.Empty(t, del.ProjectedPath, "no projection for a DM") assert.Empty(t, call.StructuredMessage.Attachments, "no scratchpad path is listed") + assert.Empty(t, call.StructuredMessage.AttachmentMounts, "no attachment_mounts for artifact attachment") plan := f.srv.attachmentDelivery().Plan(context.Background(), f.aa, call.StructuredMessage.AttachmentDeliveries) require.Len(t, plan, 1) assert.Equal(t, attachmentInboxPath(resp.ID, "dm.txt"), plan[0].InboxPath) @@ -100,15 +100,18 @@ func TestAttachmentAudience_LocalDefaults_DMAndTopic(t *testing.T) { require.Equal(t, http.StatusOK, got.status, got.body) assert.Equal(t, "dm bytes", got.body) - // Project topic thread: inbox plus projection. + // Project topic thread: inbox only (no scratchpad copy, ptone/scion#9694). inTopic := f.uploadAs(t, f.ua, f.projA.ID, "topic.txt", "topic bytes") resp = f.sendWith(t, f.ua, f.topicA, inTopic) - assert.FileExists(t, filepath.Join(stagingDir, inTopic, "topic.txt"), "a project topic thread is projected") + assert.NoDirExists(t, filepath.Join(stagingDir, inTopic), "no scratchpad copy of a project topic artifact attachment") call = callTo(t, disp, f.aa) require.Len(t, call.StructuredMessage.AttachmentDeliveries, 1) assert.Equal(t, resp.ID, call.StructuredMessage.AttachmentDeliveries[0].MessageID) - assert.Equal(t, "/scion-volumes/scratchpad/.attachments/_webchat/"+inTopic+"/topic.txt", - call.StructuredMessage.AttachmentDeliveries[0].ProjectedPath) + assert.Empty(t, call.StructuredMessage.Attachments, "no scratchpad path is listed") + assert.Empty(t, call.StructuredMessage.AttachmentMounts, "no attachment_mounts for artifact attachment") + plan = f.srv.attachmentDelivery().Plan(context.Background(), f.aa, call.StructuredMessage.AttachmentDeliveries) + require.Len(t, plan, 1) + assert.Equal(t, attachmentInboxPath(resp.ID, "topic.txt"), plan[0].InboxPath) got = f.download(t, f.ua, inTopic) require.Equal(t, http.StatusOK, got.status, got.body) assert.Equal(t, "topic bytes", got.body) diff --git a/pkg/hub/attachments_nfs_test.go b/pkg/hub/attachments_nfs_test.go index 8cd3a8f769f..5f45c575322 100644 --- a/pkg/hub/attachments_nfs_test.go +++ b/pkg/hub/attachments_nfs_test.go @@ -312,14 +312,14 @@ func TestStageChatAttachments_LegacyOnNFS_OnlyWholeProjectAudience(t *testing.T) require.NoError(t, wcs.CreateTopic(ctx, WebChatTopic{ID: topicID, ProjectID: project.ID, Name: "t", CreatedBy: "u1", CreatedAt: time.Now().UTC()})) dmRef := saveLegacyAttachment(t, srv, project.ID, "dm.txt", "dm bytes") - paths, mounts := srv.stageChatAttachments(ctx, "dm:user:u1:agent:a1", project.ID, api.NewUUID(), []AttachmentRef{dmRef}) + paths, mounts := srv.stageChatAttachments(ctx, "dm:user:u1:agent:a1", project.ID, []AttachmentRef{dmRef}) require.Len(t, paths, 1) assert.NotContains(t, paths[0], "/scion-volumes/", "a DM legacy attachment gets the hub-local path, not a scratchpad copy") assert.Empty(t, mounts) assert.NoDirExists(t, filepath.Join(leaf, ".attachments", "_webchat", dmRef.ID)) topicRef := saveLegacyAttachment(t, srv, project.ID, "topic.txt", "topic bytes") - paths, mounts = srv.stageChatAttachments(ctx, topicID, project.ID, api.NewUUID(), []AttachmentRef{topicRef}) + paths, mounts = srv.stageChatAttachments(ctx, topicID, project.ID, []AttachmentRef{topicRef}) require.Len(t, paths, 1) assert.Equal(t, "/scion-volumes/scratchpad/.attachments/_webchat/"+topicRef.ID+"/topic.txt", paths[0]) assert.Equal(t, attachmentSharedDirName, mounts[paths[0]]) diff --git a/pkg/hub/attachments_p4_test.go b/pkg/hub/attachments_p4_test.go index 2033f4a43e0..575393182e5 100644 --- a/pkg/hub/attachments_p4_test.go +++ b/pkg/hub/attachments_p4_test.go @@ -479,42 +479,17 @@ func TestAgentAttachmentRelPath_TargetsFromAuthority(t *testing.T) { } } -// --------------------------------------------------------------------------- -// Delivery plan: the projection is listed for every state but withheld -// --------------------------------------------------------------------------- - -func TestAttachmentPlan_ProjectionCopiedUnlessWithheld(t *testing.T) { - del := messages.AttachmentDelivery{ - ArtifactID: "a1", MessageID: "m1", Name: "x.txt", - ProjectedPath: "/scion-volumes/scratchpad/.attachments/_webchat/a1/x.txt", ProjectedMount: "scratchpad", - } - for _, state := range []string{messages.AttachmentDeliverable, messages.AttachmentUndeliverableRuntime, messages.AttachmentWithheld} { - e := messages.AttachmentPlanEntry{Delivery: del, State: state} - applyProjection(&e) - if state == messages.AttachmentWithheld { - assert.Empty(t, e.ProjectedPath, state) - assert.Empty(t, e.ProjectedMount, state) - continue - } - assert.Equal(t, del.ProjectedPath, e.ProjectedPath, state) - assert.Equal(t, "scratchpad", e.ProjectedMount, state) - } -} - -// TestProjection_OnlyChatV2SendPathProjects pins, at the source level, that -// the scratchpad projection of artifact attachments is reachable from one -// place only: stageChatAttachments is called only by -// sendAgentRouted (every chat v2 send, scheduled sends and promotions -// included, goes through it; mention copies reuse its result), and -// AttachmentRef.projectedPath/projectedMount are assigned only inside -// stageChatAttachments, behind its projectionAudienceIsProject check. -func TestProjection_OnlyChatV2SendPathProjects(t *testing.T) { +// TestStageChatAttachments_OnlyCalledFromSendAgentRouted pins, at the source +// level, that legacy scratchpad staging (stageChatAttachments) is called only +// by sendAgentRouted (every chat v2 send, scheduled sends and promotions +// included, goes through it; mention copies reuse its result). +func TestStageChatAttachments_OnlyCalledFromSendAgentRouted(t *testing.T) { // pkgmove:scan-covers guardScanSubdirs - // scanned through guardScanSubdirs; guards stageChatAttachments call sites and projectedPath/projectedMount writes. + // scanned through guardScanSubdirs; guards stageChatAttachments call sites. paths, err := globGuardScanDirs(".", "*.go") require.NoError(t, err) fset := token.NewFileSet() - var callers, assigners []string + var callers []string for _, path := range paths { if strings.HasSuffix(path, "_test.go") { continue @@ -527,29 +502,16 @@ func TestProjection_OnlyChatV2SendPathProjects(t *testing.T) { continue } ast.Inspect(fn, func(n ast.Node) bool { - switch x := n.(type) { - case *ast.CallExpr: + if x, ok := n.(*ast.CallExpr); ok { if sel, ok := x.Fun.(*ast.SelectorExpr); ok && sel.Sel.Name == "stageChatAttachments" { callers = append(callers, fn.Name.Name) } - case *ast.AssignStmt: - for _, lhs := range x.Lhs { - if sel, ok := lhs.(*ast.SelectorExpr); ok && (sel.Sel.Name == "projectedPath" || sel.Sel.Name == "projectedMount") { - assigners = append(assigners, fn.Name.Name+"."+sel.Sel.Name) - } - } - case *ast.KeyValueExpr: - if id, ok := x.Key.(*ast.Ident); ok && (id.Name == "projectedPath" || id.Name == "projectedMount") { - assigners = append(assigners, fn.Name.Name+"."+id.Name+"(literal)") - } } return true }) } } assert.Equal(t, []string{"sendAgentRouted"}, callers, "stageChatAttachments call sites") - assert.ElementsMatch(t, []string{"stageChatAttachments.projectedPath", "stageChatAttachments.projectedMount"}, assigners, - "projectedPath/projectedMount are set only by stageChatAttachments") } // failingLinksWCS fails every link lookup. diff --git a/pkg/hub/attachments_refs_test.go b/pkg/hub/attachments_refs_test.go index c432ca23ee8..8a487273b8a 100644 --- a/pkg/hub/attachments_refs_test.go +++ b/pkg/hub/attachments_refs_test.go @@ -289,15 +289,10 @@ func hubCallerFuncs(t *testing.T, names ...string) map[string][]string { return out } -// TestOpenBoundAttachment_OnlyFromSendPath: OpenBoundAttachment checks no -// caller, so pkg/hub calls it only from stageArtifactAttachment, and that -// only from stageChatAttachments (design section 2). -func TestOpenBoundAttachment_OnlyFromSendPath(t *testing.T) { - sites := hubCallerFuncs(t, "OpenBoundAttachment", "stageArtifactAttachment") - require.Equal(t, []string{"attachments_artifacts.go:stageArtifactAttachment"}, sites["OpenBoundAttachment"]) - require.Equal(t, []string{"handlers_chat_v2.go:stageChatAttachments"}, sites["stageArtifactAttachment"]) - // The capability redemption route is the one other caller-less read of - // a bound attachment (ptone/scion#4596, section 8.3). +// TestServeBoundAttachment_OnlyFromDeliveryRoute: ServeBoundAttachment is +// the sole caller-less read of a bound attachment (ptone/scion#4596, +// section 8.3), called only from the capability redemption route. +func TestServeBoundAttachment_OnlyFromDeliveryRoute(t *testing.T) { require.Equal(t, []string{"attachment_delivery.go:handleAttachmentDelivery"}, hubCallerFuncs(t, "ServeBoundAttachment")["ServeBoundAttachment"]) } diff --git a/pkg/hub/attachments_send.go b/pkg/hub/attachments_send.go index 892ed286903..f3e46890baa 100644 --- a/pkg/hub/attachments_send.go +++ b/pkg/hub/attachments_send.go @@ -181,7 +181,6 @@ func attachmentDeliveries(messageID string, refs []AttachmentRef) []messages.Att out = append(out, messages.AttachmentDelivery{ ArtifactID: ref.ID, MessageID: messageID, Name: ref.Name, MimeType: ref.MimeType, Size: ref.Size, SHA256: ref.sha256, - ProjectedPath: ref.projectedPath, ProjectedMount: ref.projectedMount, }) } return out diff --git a/pkg/hub/attachments_staging_test.go b/pkg/hub/attachments_staging_test.go index cfcc7adb88d..ce21cfa727a 100644 --- a/pkg/hub/attachments_staging_test.go +++ b/pkg/hub/attachments_staging_test.go @@ -354,7 +354,7 @@ func TestResolveAttachmentStaging_UnknownProject(t *testing.T) { func TestStageChatAttachments_LegacyOnLocal_DMStillStaged(t *testing.T) { srv, _, project, sharedDir := agentAttachmentServer(t) ref := saveLegacyAttachment(t, srv, project.ID, "dm.txt", "dm bytes") - paths, mounts := srv.stageChatAttachments(context.Background(), "dm:user:u1:agent:a1", project.ID, api.NewUUID(), []AttachmentRef{ref}) + paths, mounts := srv.stageChatAttachments(context.Background(), "dm:user:u1:agent:a1", project.ID, []AttachmentRef{ref}) require.Len(t, paths, 1) assert.Equal(t, "/scion-volumes/scratchpad/.attachments/_webchat/"+ref.ID+"/dm.txt", paths[0]) assert.Equal(t, attachmentSharedDirName, mounts[paths[0]]) diff --git a/pkg/hub/capability_keyring_test.go b/pkg/hub/capability_keyring_test.go index f8d0881cfe9..dc9759ec8cb 100644 --- a/pkg/hub/capability_keyring_test.go +++ b/pkg/hub/capability_keyring_test.go @@ -1262,13 +1262,11 @@ func TestCapabilityKeyring_DeliveryIssuanceClosed(t *testing.T) { assertNoCapabilityKeyMaterial(t, logs.String(), before) } -// TestCapabilityKeyring_DeliveryWithProjectionStillSigned: a deliverable -// plan entry that carries a scratchpad projection (applyProjection) is -// issued a versioned capability like any other: it redeems on the other -// replica with the file bytes, and the same token with its payload altered -// is refused without spending the nonce. The projection is plan metadata; -// the signed payload is unchanged by it. -func TestCapabilityKeyring_DeliveryWithProjectionStillSigned(t *testing.T) { +// TestCapabilityKeyring_DeliveryCapabilitySignedAndTamperRejected: a +// deliverable plan entry is issued a versioned capability that redeems on the +// other replica with the file bytes, and the same token with its payload +// altered is refused without spending the nonce. +func TestCapabilityKeyring_DeliveryCapabilitySignedAndTamperRejected(t *testing.T) { allowVersionedRings(t) f := setupCapDeliveryFixture(t) clk := &krClock{t: krT0} @@ -1278,11 +1276,6 @@ func TestCapabilityKeyring_DeliveryWithProjectionStillSigned(t *testing.T) { plan := append([]messages.AttachmentPlanEntry(nil), f.call.StructuredMessage.AttachmentPlan...) require.Len(t, plan, 1) require.Equal(t, messages.AttachmentDeliverable, plan[0].State) - plan[0].Delivery.ProjectedPath = "/test-only/shared/.attachments/" + plan[0].Delivery.ArtifactID + "/report.txt" - plan[0].Delivery.ProjectedMount = "test-only-shared" - applyProjection(&plan[0]) - require.Equal(t, plan[0].Delivery.ProjectedPath, plan[0].ProjectedPath) - require.Equal(t, "test-only-shared", plan[0].ProjectedMount) wire := a.attachmentDelivery().Issue(context.Background(), f.call.Agent, f.call.Agent.RuntimeBrokerID, plan) require.Len(t, wire, 1) token := tokenOf(t, wire[0]) @@ -1293,8 +1286,7 @@ func TestCapabilityKeyring_DeliveryWithProjectionStillSigned(t *testing.T) { // token stays well-formed and its refusal comes from the MAC check. payload, err := base64.RawURLEncoding.Strict().DecodeString(parts[2]) require.NoError(t, err) - // The signed payload carries only the capability fields; the projection - // is not part of it. + // The signed payload carries only the capability fields. var fields map[string]json.RawMessage require.NoError(t, json.Unmarshal(payload, &fields)) keys := make([]string, 0, len(fields)) @@ -1302,7 +1294,6 @@ func TestCapabilityKeyring_DeliveryWithProjectionStillSigned(t *testing.T) { keys = append(keys, k) } assert.ElementsMatch(t, []string{"a", "m", "g", "b", "e", "n"}, keys) - assert.NotContains(t, string(payload), "test-only-shared") // Flip a byte inside the artifact ID value (never the nonce), so the // refusal below cannot depend on the field lengths. at := bytes.Index(payload, []byte(`"a":"`)) diff --git a/pkg/hub/handlers_broker_inbound_attachments_test.go b/pkg/hub/handlers_broker_inbound_attachments_test.go index f43974a831e..8a71e1801de 100644 --- a/pkg/hub/handlers_broker_inbound_attachments_test.go +++ b/pkg/hub/handlers_broker_inbound_attachments_test.go @@ -579,8 +579,6 @@ func TestBrokerInbound_AttachmentIDsDelivered(t *testing.T) { assert.Equal(t, messages.AttachmentDeliverable, entry.State) assert.Equal(t, ids[0], entry.Delivery.ArtifactID) assert.True(t, strings.HasPrefix(entry.InboxPath, attachmentInboxDir), entry.InboxPath) - assert.Empty(t, entry.ProjectedPath, "no scratchpad projection for a plugin conversation") - assert.Empty(t, entry.ProjectedMount) // The id is now bound to the stored message, which was persisted. _, state, err := f.srv.attachmentService().UsableAttachment(context.Background(), ids[0], artifacts.PrincipalKindUser, f.ua.ID) @@ -676,7 +674,6 @@ func TestBrokerInbound_AttachmentsNotReadableByOtherUsersAgent(t *testing.T) { calls := f.disp.getCalls() require.Len(t, calls, 1) del := calls[0].StructuredMessage.AttachmentPlan[0].Delivery - assert.Empty(t, del.ProjectedPath) project := f.projA.ID assert.False(t, svc.MayReadAttachments(attachmentDecisionForRecipient(bAgent), del.MessageID, &project)) plan := f.srv.attachmentDelivery().Plan(ctx, bAgent, []messages.AttachmentDelivery{del}) diff --git a/pkg/hub/handlers_chat_v2.go b/pkg/hub/handlers_chat_v2.go index 1fa9d639542..ed9aca3a259 100644 --- a/pkg/hub/handlers_chat_v2.go +++ b/pkg/hub/handlers_chat_v2.go @@ -62,7 +62,6 @@ import ( "github.com/GoogleCloudPlatform/scion/pkg/agent/state" "github.com/GoogleCloudPlatform/scion/pkg/api" "github.com/GoogleCloudPlatform/scion/pkg/artifacts" - "github.com/GoogleCloudPlatform/scion/pkg/experiments" "github.com/GoogleCloudPlatform/scion/pkg/messages" "github.com/GoogleCloudPlatform/scion/pkg/messaging" "github.com/GoogleCloudPlatform/scion/pkg/projectfs" @@ -1322,44 +1321,28 @@ func (s *Server) handleConversationSend(w http.ResponseWriter, r *http.Request, } } -// stageChatAttachments makes a message's attachments visible to agents, -// after the message is authorized and stored, and returns the entries for -// the message's legacy attachment list with, for each entry that is a path +// stageChatAttachments makes legacy (AttachmentStore) attachments visible to +// agents, after the message is authorized and stored, and returns the entries +// for the message's legacy attachment list with, for each entry that is a path // in a shared dir, that dir's name (StructuredMessage.AttachmentMounts). // -// The hub's attachment stores (the artifact service, the hub-private -// AttachmentStore) are not mounted into agent containers, so each file is -// projected into the project's scratchpad shared dir, resolved through the -// layout authority (resolveAttachmentStaging, ptone/scion#5827): -// - an attachment stored as an artifact while hub.attachment_artifacts is -// on (read now, at send time) reaches the recipient by delivery into its -// home and adds no legacy entry. It is projected only when the message's -// read audience is the whole project (a project topic thread, key): -// a projection is readable by every agent that mounts the scratchpad, -// so a direct or group conversation, whose readers are its -// participants, gets inbox delivery only. The projection is recorded on -// refs[i] (projectedPath, projectedMount) and listed after the inbox -// path; -// - an attachment stored as an artifact (uploaded while the experiment -// was on) and sent while it is off is still delivered into the home; -// for a project topic thread it is also staged from its stored bytes -// and listed as a legacy entry, and otherwise it gets no scratchpad -// copy; -// - an AttachmentStore attachment is staged from the hub-private store. -// On a shared backend it is staged only when the whole project reads -// the message; on the local backend for every send. When it is not -// staged the hub-local path is sent, which host-process agents can -// still read. +// Artifact-backed attachments (ref.artifact == true) are skipped here: they +// reach each recipient exclusively via inbox delivery (~/.scion/inbox//), +// with no scratchpad copy (ptone/scion#9694). Sibling agents in project +// conversations fetch them via `scion conversation get-message --save-attachments`. // -// Without artifact delivery (the last case) staging is the only way a -// containerised agent reads the file. On the local backend it therefore -// happens for every send, so on a workstation hub a DM's attachment is -// readable by the project's other agents: a known limitation that ends -// when the hub stores attachments as artifacts. +// Legacy AttachmentStore attachments are staged from the hub-private store +// into the project's scratchpad shared dir (resolveAttachmentStaging): +// - On a shared backend (NFS) they are staged only when the whole project +// reads the message (projectionAudienceIsProject); otherwise the hub-local +// path is sent, which host-process agents can still read. +// - On the local backend (workstation) they are staged for every send, since +// staging is the only way a containerised agent reads a legacy attachment +// (a known workstation limitation that ends when attachments are stored as +// artifacts). // -// key is the message's thread key and messageID the stored message the -// attachments are bound to. -func (s *Server) stageChatAttachments(ctx context.Context, key, projectID, messageID string, attachmentRefs []AttachmentRef) ([]string, map[string]string) { +// key is the message's thread key. +func (s *Server) stageChatAttachments(ctx context.Context, key, projectID string, attachmentRefs []AttachmentRef) ([]string, map[string]string) { if len(attachmentRefs) == 0 { return nil, nil } @@ -1378,7 +1361,6 @@ func (s *Server) stageChatAttachments(ctx context.Context, key, projectID, messa mounts[p] = staging.mount.Name } staging := s.resolveAttachmentStaging(ctx, projectID) - artifactsOn := s.experimentEnabled(experiments.AttachmentArtifacts) projectAudience := -1 // unknown until an attachment asks wholeProject := func() bool { if projectAudience < 0 { @@ -1392,30 +1374,9 @@ func (s *Server) stageChatAttachments(ctx context.Context, key, projectID, messa for i := range attachmentRefs { ref := attachmentRefs[i] if ref.artifact { - // An attachment stored as an artifact is delivered into the - // recipient's home (ptone/scion#4596) whatever the experiment - // says now, so a scratchpad copy is only ever an addition for - // sibling agents, made only when they all read the message. - if !wholeProject() { - continue - } - staged, err := s.stageArtifactAttachment(ctx, staging, messageID, ref) - if artifactsOn { - switch { - case err == nil: - attachmentRefs[i].projectedPath, attachmentRefs[i].projectedMount = staged, staging.mount.Name - case !errors.Is(err, errNoAttachmentStaging): - s.messageLog.Error("Failed to project attachment into the scratchpad", - "attachment", ref.ID, "error", err) - } - continue - } - if err != nil { - s.messageLog.Error("Failed to stage attachment for agent", - "attachment", ref.ID, "error", err) - continue - } - addStaged(staged, staging) + // Artifact-backed attachments are delivered exclusively into each + // recipient's inbox (~/.scion/inbox//), regardless of + // whether hub.attachment_artifacts is currently on or off. continue } if localAS == nil { @@ -2160,14 +2121,16 @@ func (s *Server) sendAgentRouted(ctx context.Context, key, projectID string, use // Attachments stored as artifacts move to the message's scope now that // it is stored; one that cannot be bound is left out of the message. attachmentRefs = s.bindChatAttachments(ctx, artifacts.PrincipalKindUser, user.ID(), storeMsg.ID, s.bindProject(ctx, storeMsg, attachmentRefs), attachmentRefs) - // Attachment files are projected into the project's scratchpad only - // now: every check that can refuse the send (authorization, validation, - // wake, conversation resolution, persistence) has passed. - stagedPaths, stagedMounts := s.stageChatAttachments(ctx, key, projectID, storeMsg.ID, attachmentRefs) + // Legacy AttachmentStore files are staged into the project's scratchpad + // only now: every check that can refuse the send (authorization, validation, + // wake, conversation resolution, persistence) has passed. Artifact-backed + // attachments are skipped by stageChatAttachments and delivered only into + // each recipient's inbox. + stagedPaths, stagedMounts := s.stageChatAttachments(ctx, key, projectID, attachmentRefs) msg.Attachments = append(msg.Attachments, stagedPaths...) msg.AttachmentMounts = stagedMounts - // The bound ones are delivered into the agent's home (ptone/scion#4596), - // with their scratchpad projection listed after the inbox path. + // Artifact-backed attachments are delivered into the agent's home + // (~/.scion/inbox//, ptone/scion#4596). msg.AttachmentDeliveries = attachmentDeliveries(storeMsg.ID, attachmentRefs) // The row was stored with the optimistic "dispatched" state, which the diff --git a/pkg/messages/types.go b/pkg/messages/types.go index e6db700a14d..b37c2327648 100644 --- a/pkg/messages/types.go +++ b/pkg/messages/types.go @@ -502,12 +502,6 @@ type AttachmentDelivery struct { MimeType string Size int64 SHA256 string - // ProjectedPath, when set, is the container path of the attachment's - // projection into shared dir ProjectedMount (the scratchpad, - // ptone/scion#5830), where sibling agents of the project find it. It is - // listed after the inbox path, never instead of it. - ProjectedPath string - ProjectedMount string } // Attachment plan states (ptone/scion#4596): what the hub decided, for one @@ -535,12 +529,6 @@ type AttachmentPlanEntry struct { // Name is the hub-reduced file name. Name string State string - // ProjectedPath and ProjectedMount are the delivery's projection into a - // shared dir (AttachmentDelivery.ProjectedPath), set for every state - // but withheld. The envelope lists the projection as a second, - // self-describing entry after the inbox path. - ProjectedPath string - ProjectedMount string } // WireAttachment is one attachment of a message request the hub sends to diff --git a/pkg/messaging/render_delivery.go b/pkg/messaging/render_delivery.go index 20e20de9b7d..8acd8980cf1 100644 --- a/pkg/messaging/render_delivery.go +++ b/pkg/messaging/render_delivery.go @@ -120,16 +120,9 @@ func RenderDeliveryText(in RenderDeliveryInput) string { } } for _, e := range in.Plan { - // The inbox path comes first: it is valid on every runtime. The - // projection follows, tagged with its shared dir, so a recipient - // whose runtime does not mount that dir is never left with only a - // dangling path. if e.State == messages.AttachmentDeliverable { msg.Attachments = append(msg.Attachments, AttachmentRef{Path: e.InboxPath, Name: e.Name}) } - if e.State != messages.AttachmentWithheld && e.ProjectedPath != "" { - msg.Attachments = append(msg.Attachments, AttachmentRef{Path: e.ProjectedPath, Name: e.Name, Mount: e.ProjectedMount}) - } } // Override timestamp if we have a real one from the persisted row. @@ -257,9 +250,8 @@ func RenderDeliveryTextWithLookup( // appendPlanLines appends to body, after a blank line, one line per // attachment of plan the recipient's runtime cannot receive and, with // paths, one "Attachment: " line per deliverable attachment (the -// plain form, which has no envelope to list them in), plus one line per -// non-withheld attachment that is also projected into a shared dir -// (AttachmentProjectedLine). Withheld entries are not mentioned. body is returned unchanged when there is nothing to add. +// plain form, which has no envelope to list them in). Withheld entries are +// not mentioned. body is returned unchanged when there is nothing to add. func appendPlanLines(body string, plan []messages.AttachmentPlanEntry, paths bool) string { var lines []string for _, e := range plan { @@ -272,9 +264,6 @@ func appendPlanLines(body string, plan []messages.AttachmentPlanEntry, paths boo lines = append(lines, AttachmentNotDeliveredLine(e.Name, e.Delivery.Size, "the recipient's runtime cannot receive attachments")) } - if e.State != messages.AttachmentWithheld && e.ProjectedPath != "" { - lines = append(lines, AttachmentProjectedLine(e.Name, e.ProjectedPath, e.ProjectedMount)) - } } if len(lines) == 0 { return body @@ -282,15 +271,6 @@ func appendPlanLines(body string, plan []messages.AttachmentPlanEntry, paths boo return body + "\n\n" + strings.Join(lines, "\n") } -// AttachmentProjectedLine is the line a recipient reads for an attachment -// that is also projected into a shared dir (ptone/scion#5827): the -// inbox path stays the one to use; the projection is where sibling agents -// that mount the shared dir find the same file. -func AttachmentProjectedLine(name, path, mount string) string { - return "Attachment " + name + " is also visible to sibling agents at " + path + - " (shared dir " + mount + ", only in containers that mount it)." -} - // Reasons a broker gives for an attachment that did not land in the // recipient's home (ptone/scion#4596): in the not-delivered line the agent // reads, and in the per-file outcomes the hub counts. @@ -323,9 +303,7 @@ func FormatAttachmentSize(n int64) string { // ApplyAttachmentPlanLegacy applies plan to msg for the legacy envelope, // which the broker formats itself when the hub renders no delivery text: // deliverable inbox paths are appended to msg.Attachments, and not-delivered -// and projection lines to msg.Msg (the legacy attachment list carries no -// mount, so a projection is described in the body only). msg must be the -// per-recipient message being dispatched. +// lines to msg.Msg. msg must be the per-recipient message being dispatched. func ApplyAttachmentPlanLegacy(msg *messages.StructuredMessage, plan []messages.AttachmentPlanEntry) { if msg == nil { return diff --git a/pkg/messaging/render_delivery_projection_test.go b/pkg/messaging/render_delivery_projection_test.go index febf919b40c..fbc0c0c8bdc 100644 --- a/pkg/messaging/render_delivery_projection_test.go +++ b/pkg/messaging/render_delivery_projection_test.go @@ -22,13 +22,14 @@ import ( "github.com/GoogleCloudPlatform/scion/pkg/messages" ) -// Envelope shape for scratchpad projections (ptone/scion#5827): -// the inbox path is the primary entry, the projection a second, -// self-describing entry tagged with its mount. +// Envelope shape for artifact-backed and legacy attachments (ptone/scion#9694): +// artifact-backed attachments are listed once at their inbox path with no +// scratchpad projection, no attachment_mounts, and no sibling-agents note; +// legacy staged paths still carry attachment_mounts. const ( - testInboxPath = "~/.scion/inbox/m1/a.png" - testProjectedPath = "/scion-volumes/scratchpad/.attachments/_webchat/art1/a.png" + testInboxPath = "~/.scion/inbox/m1/a.png" + testLegacyStaged = "/scion-volumes/scratchpad/.attachments/_webchat/art1/a.png" ) func projectionTestMsg(plain bool) *messages.StructuredMessage { @@ -43,13 +44,11 @@ func projectionTestMsg(plain bool) *messages.StructuredMessage { } } -func projectedEntry(state string) messages.AttachmentPlanEntry { +func planEntry(state string) messages.AttachmentPlanEntry { e := messages.AttachmentPlanEntry{ - Delivery: messages.AttachmentDelivery{ArtifactID: "art1", MessageID: "m1", Name: "a.png", Size: 10}, - Name: "a.png", - State: state, - ProjectedPath: testProjectedPath, - ProjectedMount: "scratchpad", + Delivery: messages.AttachmentDelivery{ArtifactID: "art1", MessageID: "m1", Name: "a.png", Size: 10}, + Name: "a.png", + State: state, } if state != messages.AttachmentWithheld { e.InboxPath = testInboxPath @@ -57,82 +56,86 @@ func projectedEntry(state string) messages.AttachmentPlanEntry { return e } -func TestRenderDeliveryText_ProjectionAfterInboxWithMount(t *testing.T) { +func TestRenderDeliveryText_DeliverableSingleInboxEntry(t *testing.T) { env := extractDeliveryEnvelope(t, RenderDeliveryText(RenderDeliveryInput{ MessageID: "m1", Msg: projectionTestMsg(false), CreatedAt: time.Now().UTC(), - Plan: []messages.AttachmentPlanEntry{projectedEntry(messages.AttachmentDeliverable)}, + Plan: []messages.AttachmentPlanEntry{planEntry(messages.AttachmentDeliverable)}, })) - if len(env.Attachments) != 2 || env.Attachments[0] != testInboxPath || env.Attachments[1] != testProjectedPath { - t.Fatalf("attachments = %q, want [inbox, projection]", env.Attachments) + if len(env.Attachments) != 1 || env.Attachments[0] != testInboxPath { + t.Fatalf("attachments = %q, want [inbox] only", env.Attachments) } - if len(env.AttachmentMounts) != 1 || env.AttachmentMounts[testProjectedPath] != "scratchpad" { - t.Fatalf("attachment_mounts = %v, want only the projection tagged scratchpad", env.AttachmentMounts) + if len(env.AttachmentMounts) != 0 { + t.Fatalf("attachment_mounts = %v, want empty", env.AttachmentMounts) } - if !strings.Contains(env.Msg, "also visible to sibling agents at "+testProjectedPath) { - t.Fatalf("body %q does not describe the projection", env.Msg) + if strings.Contains(env.Msg, "also visible to sibling agents") { + t.Fatalf("body %q must not mention sibling-agent scratchpad projection", env.Msg) } } -func TestRenderDeliveryText_UndeliverableKeepsProjection(t *testing.T) { +func TestRenderDeliveryText_UndeliverableRuntimeHasNoScratchpadFallback(t *testing.T) { env := extractDeliveryEnvelope(t, RenderDeliveryText(RenderDeliveryInput{ MessageID: "m1", Msg: projectionTestMsg(false), CreatedAt: time.Now().UTC(), - Plan: []messages.AttachmentPlanEntry{projectedEntry(messages.AttachmentUndeliverableRuntime)}, + Plan: []messages.AttachmentPlanEntry{planEntry(messages.AttachmentUndeliverableRuntime)}, })) - if len(env.Attachments) != 1 || env.Attachments[0] != testProjectedPath { - t.Fatalf("attachments = %q, want only the projection", env.Attachments) + if len(env.Attachments) != 0 { + t.Fatalf("attachments = %q, want empty", env.Attachments) } - if env.AttachmentMounts[testProjectedPath] != "scratchpad" { - t.Fatalf("attachment_mounts = %v", env.AttachmentMounts) + if len(env.AttachmentMounts) != 0 { + t.Fatalf("attachment_mounts = %v, want empty", env.AttachmentMounts) } if !strings.Contains(env.Msg, "Attachment not delivered: a.png") { t.Fatalf("body %q lacks the not-delivered line", env.Msg) } + if strings.Contains(env.Msg, "also visible to sibling agents") { + t.Fatalf("body %q must not mention sibling-agent scratchpad projection", env.Msg) + } } -func TestRenderDeliveryText_WithheldMentionsNoProjection(t *testing.T) { +func TestRenderDeliveryText_WithheldMentionsNothing(t *testing.T) { text := RenderDeliveryText(RenderDeliveryInput{ MessageID: "m1", Msg: projectionTestMsg(false), CreatedAt: time.Now().UTC(), - Plan: []messages.AttachmentPlanEntry{projectedEntry(messages.AttachmentWithheld)}, + Plan: []messages.AttachmentPlanEntry{planEntry(messages.AttachmentWithheld)}, }) - if strings.Contains(text, testProjectedPath) || strings.Contains(text, "a.png") { + if strings.Contains(text, testInboxPath) || strings.Contains(text, "a.png") { t.Fatalf("a withheld attachment must not be mentioned:\n%s", text) } } -func TestRenderDeliveryText_PlainListsProjectionLine(t *testing.T) { +func TestRenderDeliveryText_PlainListsInboxOnly(t *testing.T) { text := RenderDeliveryText(RenderDeliveryInput{ MessageID: "m1", Msg: projectionTestMsg(true), CreatedAt: time.Now().UTC(), - Plan: []messages.AttachmentPlanEntry{projectedEntry(messages.AttachmentDeliverable)}, + Plan: []messages.AttachmentPlanEntry{planEntry(messages.AttachmentDeliverable)}, }) - inbox := strings.Index(text, "Attachment: "+testInboxPath) - proj := strings.Index(text, "also visible to sibling agents at "+testProjectedPath) - if inbox < 0 || proj < 0 || proj < inbox { - t.Fatalf("plain text must list the inbox path, then the projection:\n%s", text) + if !strings.Contains(text, "Attachment: "+testInboxPath) { + t.Fatalf("plain text must list the inbox path:\n%s", text) + } + if strings.Contains(text, "also visible to sibling agents") { + t.Fatalf("plain text must not include sibling-agent projection line:\n%s", text) } } func TestRenderDeliveryText_LegacyStagedPathTaggedWithMount(t *testing.T) { msg := projectionTestMsg(false) - msg.Attachments = []string{testProjectedPath, "/home/hub/.scion/attachments/p/id/b.txt"} - msg.AttachmentMounts = map[string]string{testProjectedPath: "scratchpad"} + msg.Attachments = []string{testLegacyStaged, "/home/hub/.scion/attachments/p/id/b.txt"} + msg.AttachmentMounts = map[string]string{testLegacyStaged: "scratchpad"} env := extractDeliveryEnvelope(t, RenderDeliveryText(RenderDeliveryInput{ MessageID: "m1", Msg: msg, CreatedAt: time.Now().UTC(), })) if len(env.Attachments) != 2 { t.Fatalf("attachments = %q", env.Attachments) } - if len(env.AttachmentMounts) != 1 || env.AttachmentMounts[testProjectedPath] != "scratchpad" { + if len(env.AttachmentMounts) != 1 || env.AttachmentMounts[testLegacyStaged] != "scratchpad" { t.Fatalf("attachment_mounts = %v, want the staged path only", env.AttachmentMounts) } } -func TestApplyAttachmentPlanLegacy_ProjectionInBodyOnly(t *testing.T) { +func TestApplyAttachmentPlanLegacy_InboxOnly(t *testing.T) { msg := projectionTestMsg(false) - ApplyAttachmentPlanLegacy(msg, []messages.AttachmentPlanEntry{projectedEntry(messages.AttachmentDeliverable)}) + ApplyAttachmentPlanLegacy(msg, []messages.AttachmentPlanEntry{planEntry(messages.AttachmentDeliverable)}) if len(msg.Attachments) != 1 || msg.Attachments[0] != testInboxPath { t.Fatalf("legacy attachments = %q, want the inbox path only", msg.Attachments) } - if !strings.Contains(msg.Msg, "also visible to sibling agents at "+testProjectedPath) { - t.Fatalf("legacy body %q does not describe the projection", msg.Msg) + if strings.Contains(msg.Msg, "also visible to sibling agents") { + t.Fatalf("legacy body %q must not mention sibling-agent scratchpad projection", msg.Msg) } }