Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion cmd/docbank/media.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,13 @@ import (
"encoding/hex"
"encoding/json/v2"
"errors"
"fmt"
"io"
"mime"
"os"
"path/filepath"
"strings"
"uuid"

"github.com/spf13/cobra"

Expand Down Expand Up @@ -97,6 +99,23 @@ var mediaStatusCmd = &cobra.Command{Use: "status <source-id>", Short: "Show curr
return writeCLIJSON(cmd.OutOrStdout(), receipt)
}}

var mediaOperationCmd = &cobra.Command{Use: "operation <operation-id>", Short: "Show a saved recording-link receipt",
Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
operationID, err := uuid.Parse(args[0])
if err != nil {
return usageError(fmt.Errorf("operation ID must be a UUID: %w", err))
}
c, err := daemonconn.Ensure(cmd.Context())
if err != nil {
return err
}
receipt, err := c.MediaOperationReceipt(cmd.Context(), operationID)
if err != nil {
return err
}
return writeCLIJSON(cmd.OutOrStdout(), receipt)
}}

var mediaTranscriptCmd = &cobra.Command{Use: "transcript <source-id>", Short: "Read one exact retained transcript",
Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
if mediaSourceVersionID == "" || mediaContentVersionID == "" {
Expand Down Expand Up @@ -321,7 +340,7 @@ func init() {
mediaConsentRevokeCmd.Flags().StringVar(&mediaOrigin, "origin", "", "registered origin ID")
mediaOccurrencesCmd.AddCommand(mediaOccurrencesListCmd, mediaOccurrencesDeclareCmd, mediaOccurrencesRevokeCmd)
mediaConsentCmd.AddCommand(mediaConsentGrantCmd, mediaConsentRevokeCmd)
mediaCmd.AddCommand(mediaSubmitCmd, mediaListCmd, mediaStatusCmd, mediaTranscriptCmd, mediaRetryCmd, mediaImportCmd,
mediaCmd.AddCommand(mediaSubmitCmd, mediaListCmd, mediaStatusCmd, mediaOperationCmd, mediaTranscriptCmd, mediaRetryCmd, mediaImportCmd,
mediaOccurrencesCmd, mediaOriginsCmd, mediaAcquisitionPlanCmd, mediaConsentCmd)
rootCmd.AddCommand(mediaCmd)
}
Expand Down
12 changes: 12 additions & 0 deletions cmd/docbank/media_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,18 @@ func TestOpenMediaUploadUsesFixedMediaTypes(t *testing.T) {
}
}

func TestMediaOperationCLIRequiresOneUUID(t *testing.T) {
t.Setenv("DOCBANK_HOME", t.TempDir())
_, err := runCLI(t, "media", "operation")
require.ErrorContains(t, err, "accepts 1 arg(s)")
// Argument validation fails before RunE starts, so main maps it to a usage exit.
require.Equal(t, exitUsage, commandExitCode(err, false))

_, err = runCLI(t, "media", "operation", "not-a-uuid")
require.ErrorContains(t, err, "operation ID must be a UUID")
require.Equal(t, exitUsage, commandExitCode(err, true))
}

func TestMediaTranscriptCLIRequiresStableVersionFlags(t *testing.T) {
t.Setenv("DOCBANK_HOME", t.TempDir())
for _, flags := range [][]string{
Expand Down
18 changes: 18 additions & 0 deletions docs/agents/integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,24 @@ docbank media transcript SOURCE_ID \
--content-version-id CONTENT_VERSION_ID
```

## Recover a lost recording-link reply

If a remote-recording submission's reply never arrived, read the saved receipt
by the operation ID you sent. You don't need to keep the original link:

```bash
curl --fail-with-body \
-H "X-Api-Key: $DOCBANK_API_KEY" \
"$DOCBANK_URL/api/v1/media/operations/00000000-0000-4000-8000-000000000001"
```

A 404 means no committed receipt was visible at that moment. A submission still
in flight can commit afterward. The equivalent CLI command is
`docbank media operation OPERATION_ID`.

The receipt records the submission as it was saved. For the source's current
state, run `docbank media status SOURCE_ID` with the receipt's `source_id`.

## Give an independent client a stable endpoint

The docbank CLI can discover an ephemeral port and per-run key from the
Expand Down
11 changes: 11 additions & 0 deletions docs/architecture/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,17 @@ the same version. A transcript from an older version cannot cover newer bytes.
Raw URLs and credential bindings never appear in receipts, errors, logs,
renditions, search results, or portable metadata.

#### Remote recording receipts

`GET /api/v1/media/operations/{operation_id}` returns the receipt saved for one
remote-recording submission under the daemon's media principal. Use it when a
`POST /api/v1/media/sources` reply was lost: the operation ID is enough, and the
caller never resends the protected link. An unknown ID, an ID owned by another
principal, and an ID from any other media operation all return `404 not_found`.
A malformed ID returns 422. Authenticated responses, including 404 and 422,
carry `Cache-Control: no-store`. A 404 describes only that read. A submission
still in flight can commit afterward.

#### Exact media transcript reads

Read one retained transcript by its complete stable identity:
Expand Down
4 changes: 4 additions & 0 deletions docs/cli-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -1424,6 +1424,7 @@ docbank media submit --file CALL.wav --operation-id UUID \
--occurrence-ref REF --revision REV
docbank media list
docbank media status SOURCE_ID
docbank media operation OPERATION_ID
docbank media transcript SOURCE_ID --source-version-id SOURCE_VERSION_ID \
--content-version-id CONTENT_VERSION_ID
docbank media import-artifact SOURCE_ID --kind media --file CALL.wav \
Expand Down Expand Up @@ -1452,6 +1453,9 @@ revision, and startup probe result. The fields are `adapter_contract`,
Self-hosted Cap registrations report `acquisition_available: false` until a
later acquisition owner exists.

`media operation` prints the saved receipt of a `media submit --reference-file`
call by its operation ID, for use after a lost reply.

`media submit` accepts bounded WAV and MP3 files. It verifies the declared
size and SHA-256 computed by the CLI, retains the original bytes, and records
the caller occurrence separately. Repeating the same bytes reuses one source
Expand Down
4 changes: 4 additions & 0 deletions docs/embedding.md
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,10 @@ if err != nil {
}
```

If that reply is lost, `Vault.RemoteRecordingReceipt` reads the saved receipt by
operation ID. `ErrNotFound` describes only that read; a submission still in
flight can commit afterward.

Obtain the file through the caller's own approved path, then attach it with
the exact SHA-256 and byte count. WAV and MP3 files use the existing media
rules. Remote MP4 originals use `video/mp4`, a `.mp4` filename, and limits of
Expand Down
24 changes: 24 additions & 0 deletions frontend/src/generated/docbank.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 22 additions & 0 deletions internal/api/routes_media.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,22 @@ func registerMediaRoutes(mux *http.ServeMux, api huma.API, d Deps, g *gate) {
return &receiptOutput{Body: fromMediaReceipt(receipt)}, nil
})

huma.Register(api, huma.Operation{OperationID: "getMediaOperationReceipt", Method: http.MethodGet,
Path: "/api/v1/media/operations/{operation_id}", Summary: "Read one remote-recording submission receipt",
Middlewares: huma.Middlewares{noStoreMediaReceipt}},
func(ctx context.Context, input *struct {
OperationID string `path:"operation_id" format:"uuid" pattern:"^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"`
}) (*receiptOutput, error) {
if d.Processing == nil {
return nil, mediaUnavailable()
}
receipt, err := d.Processing.RemoteRecordingReceipt(ctx, input.OperationID)
if err != nil {
return nil, fromMediaError(err)
}
return &receiptOutput{Body: fromMediaReceipt(receipt)}, nil
})

type transcriptOutput struct{ Body MediaTranscript }
huma.Register(api, huma.Operation{OperationID: "getMediaTranscript", Method: http.MethodGet,
Path: "/api/v1/media/sources/{source_id}/versions/{source_version_id}/transcript",
Expand Down Expand Up @@ -539,6 +555,12 @@ func fromMediaConsentReceipt(value store.MediaConsentReceipt) MediaConsentReceip
GrantID: value.GrantID, Fence: value.Fence, RevokedAt: value.RevokedAt}
}

// noStoreMediaReceipt keeps a miss from being cached; a later read can see a commit.
func noStoreMediaReceipt(ctx huma.Context, next func(huma.Context)) {
ctx.SetHeader("Cache-Control", "no-store")
next(ctx)
}

func mediaUnavailable() *Error {
return NewError(http.StatusServiceUnavailable, "capability_unavailable", "media capability is unavailable")
}
Expand Down
72 changes: 65 additions & 7 deletions internal/api/routes_media_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"testing"
"testing/synctest"
"time"
"uuid"

"github.com/stretchr/testify/require"

Expand Down Expand Up @@ -487,6 +488,69 @@ func TestMediaRouteRejectsCursorOwnedByAnotherPrincipal(t *testing.T) {
require.NoError(t, err)
require.NotEmpty(t, page.NextCursor)

otherHTTP := newOtherPrincipalMediaServer(t, catalog)
request, err := http.NewRequestWithContext(t.Context(), http.MethodGet,
otherHTTP.URL+"/api/v1/media/sources?limit=1&cursor="+url.QueryEscape(page.NextCursor), nil)
require.NoError(t, err)
response, err := otherHTTP.Client().Do(request)
require.NoError(t, err)
defer func() { require.NoError(t, response.Body.Close()) }()
require.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
}

func TestMediaOperationReceiptRecoversLostRemoteSubmission(t *testing.T) {
t.Parallel()
ts, catalog := newTestServer(t, configureMediaTestService(t))
c := daemonconn.New(ts.URL, testAPIKey)
operationID := "00000000-0000-4000-8000-000000000371"
path := "/api/v1/media/operations/" + operationID

missing, missingBody := get(t, ts, path, nil)
require.Equal(t, http.StatusNotFound, missing.StatusCode, missingBody)
require.Contains(t, missingBody, `"code":"not_found"`)
require.Equal(t, "no-store", missing.Header.Get("Cache-Control"))

submitted, err := c.SubmitRemoteRecording(t.Context(), api.MediaReferenceBody{
OperationID: operationID,
ReferenceURL: "https://recordings.invalid/private?token=SYNTHETIC-SECRET",
Occurrence: api.MediaOccurrenceBody{Ref: "lost-reply", Revision: "1"},
})
require.NoError(t, err)
recovered, err := c.MediaOperationReceipt(t.Context(), uuid.MustParse(operationID))
require.NoError(t, err)
require.Equal(t, submitted, recovered)
found, foundBody := get(t, ts, path, nil)
require.Equal(t, http.StatusOK, found.StatusCode, foundBody)
require.Equal(t, "no-store", found.Header.Get("Cache-Control"))
require.NotContains(t, foundBody, "SYNTHETIC-SECRET")
var fields map[string]any
require.NoError(t, json.Unmarshal([]byte(foundBody), &fields))
delete(fields, "$schema")
projected, err := json.Marshal(fields)
require.NoError(t, err)
var strict api.MediaReceipt
require.NoError(t, json.Unmarshal(projected, &strict, json.RejectUnknownMembers(true)))

otherHTTP := newOtherPrincipalMediaServer(t, catalog)
hidden, hiddenBody := get(t, otherHTTP, path, nil)
require.Equal(t, http.StatusNotFound, hidden.StatusCode, hiddenBody)
// $schema carries each test server's own address; the rest must match byte for byte.
require.Equal(t, strings.ReplaceAll(missingBody, ts.URL, ""), strings.ReplaceAll(hiddenBody, otherHTTP.URL, ""))

malformed, malformedBody := get(t, ts, "/api/v1/media/operations/not-a-uuid", nil)
require.Equal(t, http.StatusUnprocessableEntity, malformed.StatusCode, malformedBody)
require.Equal(t, "no-store", malformed.Header.Get("Cache-Control"))
unauthorized, unauthorizedBody := get(t, ts, path, map[string]string{"X-Api-Key": ""})
require.Equal(t, http.StatusUnauthorized, unauthorized.StatusCode, unauthorizedBody)
browser, browserBody := get(t, ts, path,
map[string]string{"X-Api-Key": "", api.WebSessionHeader: issueWebSession(t, ts)})
require.Equal(t, http.StatusForbidden, browser.StatusCode, browserBody)
require.Contains(t, browserBody, `"code":"web_session_read_only"`)
}

// newOtherPrincipalMediaServer serves the same vault under a second media principal.
func newOtherPrincipalMediaServer(t *testing.T, catalog *testStore) *httptest.Server {
t.Helper()
gate := api.NewOperationGate()
name, profile, err := processing.NewSuppliedMediaProfile(catalog.Store, catalog.Blobs, "daemon:other")
require.NoError(t, err)
Expand All @@ -508,13 +572,7 @@ func TestMediaRouteRejectsCursorOwnedByAnotherPrincipal(t *testing.T) {
otherHTTP := httptest.NewServer(otherServer.Handler())
t.Cleanup(otherHTTP.Close)
otherHTTP.Client().Transport = &apiKeyTransport{key: testAPIKey, next: otherHTTP.Client().Transport}
request, err := http.NewRequestWithContext(t.Context(), http.MethodGet,
otherHTTP.URL+"/api/v1/media/sources?limit=1&cursor="+url.QueryEscape(page.NextCursor), nil)
require.NoError(t, err)
response, err := otherHTTP.Client().Do(request)
require.NoError(t, err)
defer func() { require.NoError(t, response.Body.Close()) }()
require.Equal(t, http.StatusUnprocessableEntity, response.StatusCode)
return otherHTTP
}

func configureMediaTestService(t *testing.T) func(*api.Deps) {
Expand Down
Loading
Loading