media

package
v1.3.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 10, 2026 License: AGPL-3.0 Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package media holds the upload and download tickets, the media cache on disk, content sniffing and the size limits of spec section 10. It never holds the store's write lock.

Index

Constants

View Source
const (
	// ReasonLargerThanCacheBudget: the object is bigger than
	// `media.cache_max_bytes`, so hashing it would mean holding it entirely
	// outside the cache the budget exists to bound.
	ReasonLargerThanCacheBudget = "larger_than_cache_budget"
	// ReasonDownloadBudgetExhausted: the concurrent-download allowance of
	// spec section 12.3 is spent, and a metadata read must not queue behind
	// bytes.
	ReasonDownloadBudgetExhausted = "download_budget_exhausted"
	// ReasonBytesUnavailable: the bytes are not here and cannot be had --
	// the attachment is still `pending`, the download failed, or Google no
	// longer has it.
	ReasonBytesUnavailable = "bytes_unavailable"
)

The closed vocabulary of spec section 10.1.

View Source
const (
	// ContentDisposition is the disposition every attachment is served with.
	ContentDisposition = "attachment"

	// ContentSecurityPolicy sandboxes the response. `default-src 'none'`
	// forbids every subresource; `sandbox` drops scripts, forms, plugins and
	// same-origin, so even a type that slipped through renders inert.
	ContentSecurityPolicy = "default-src 'none'; sandbox; frame-ancestors 'none'; base-uri 'none'"

	// OctetStream is what every type not on the served list becomes.
	OctetStream = "application/octet-stream"
)

How attachment bytes are handed to a caller (spec section 10.1).

The rule is stated once, here, because it is the one place a mistake turns Agent GM's own origin into a place an attacker can host active content: a message from anybody can carry an attachment, the filename and the MIME type in it are the sender's to choose, and `GET /v1/attachments/{id}/content` serves those bytes from `AGENT_GM_PUBLIC_URL`. If that response ever said `image/svg+xml` or `text/html`, a hostile sender would have a stored XSS on the owner's own domain, delivered by a route the owner's agent is expected to fetch.

So three things travel together on every content response, and each of them is load-bearing on its own:

  • `Content-Disposition: attachment`, so a browser saves rather than renders;
  • `X-Content-Type-Options: nosniff`, so a browser does not overrule the declared type by looking at the bytes;
  • a sandboxing `Content-Security-Policy`, so anything that does get rendered has no script, no plugins and no origin of its own.
View Source
const (
	UploadPrefix   = "agm_ut_"
	DownloadPrefix = "agm_dt_"
)

Token prefixes (spec section 10.3). They are visible in the value so an owner reading a curl line can tell an upload ticket from a download one, and so a token presented at the wrong kind of endpoint is refused before anything else happens.

Variables

View Source
var ErrOutsideCache = errors.New("the cached path is outside the media cache directory")

ErrOutsideCache means a stored relative path escaped the cache directory. A path from the database is not trusted to stay inside it: a restore, a hand-edited row or a future bug should not be able to make the eviction sweep unlink something outside the cache.

View Source
var ErrTicketRefused = errors.New("the ticket is not valid for this request")

ErrTicketRefused is the single refusal.

**Every refusal is the same message whatever the reason** (spec section 10.3): a wrong audience, a bad signature, an expired ticket and a token that belongs to nobody are indistinguishable, so a status code teaches an attacker nothing about which guesses were once valid.

Functions

func Audience

func Audience(kind Kind, targetID string) string

Audience is the one thing a ticket is for: `upload:<upload_id>` or `download:<attachment_id>` (spec section 10.3). It is part of the redemption rather than a check after it, which is what makes "a token presented at the wrong URL is refused **and not spent**" true by construction: the wrong audience never reaches the row that would be spent.

func ContentTypeContradicted

func ContentTypeContradicted(declared, sniffed string) bool

ContentTypeContradicted reports whether a declared MIME type and the type sniffed from the first bytes of a body disagree in a way that means the upload is not what it said it was.

It is used at the end of a `PUT .../content` (spec section 10.2: "completion verifies the byte count, the declared digest, and the detected content type"). The comparison is deliberately coarse -- the top-level type only -- because sniffing is a heuristic and Agent GM should refuse a JPEG reservation filled with an HTML page, not quibble about `audio/mpeg` versus `audio/mp3`. An empty sniff result contradicts nothing: an unrecognisable body is not evidence of anything.

func CurlDownload

func CurlDownload(url, token, filename string) string

CurlFor renders the copy-and-paste line the two ticket responses carry (spec sections 10.1, 10.2).

**The token appears in the body and never in a URL** (section 10.3), so it cannot be captured from a proxy log or a browser history, and it is accepted only in the Authorization header -- there is no `?t=` form. That is why this builder takes the URL and the token separately and puts the token in a header: a single formatted string with the token interpolated into the URL is exactly the mistake it exists to prevent.

func CurlUpload

func CurlUpload(url, token, mimeType string) string

CurlUpload renders the upload line.

func HashToken

func HashToken(value string) string

HashToken is the at-rest form of every ticket value: SHA-256, hex. Hashing before storage and before comparison keeps the compared lengths constant, so a length difference cannot leak (spec section 12.1).

func SHA256

func SHA256(data []byte) string

SHA256 is the digest of the **decrypted** bytes (spec section 10.1), because Google carries a digest of the ciphertext, which is not what an agent comparing its downloaded copy would compute.

func SHA256Reader

func SHA256Reader(r io.Reader) (string, int64, error)

SHA256Reader is SHA256 over a stream, for a body being verified as it arrives rather than after it is all in memory.

func SHA256UnavailableReasons

func SHA256UnavailableReasons() []string

SHA256UnavailableReasons is the vocabulary, for a test that walks it.

func SHA256UnavailableWarning

func SHA256UnavailableWarning(reason string) string

SHA256UnavailableWarning is the envelope warning that accompanies the reason: `sha256_unavailable:<reason>` (spec section 10.1).

func ServedContentType

func ServedContentType(mime string) string

ServedContentType is the `Content-Type` the bytes route sends for a stored MIME type.

**SVG, HTML and every unrecognised type are served as `application/octet-stream`, never with their own type** (spec section 10.1). The stored value is not changed and is still served on the metadata route; only what this one response claims the bytes are is narrowed.

func ValidSHA256UnavailableReason

func ValidSHA256UnavailableReason(r string) bool

ValidSHA256UnavailableReason reports whether r is one of the three. It exists so a handler cannot invent a fourth: the field is a closed vocabulary and a caller branching on it should never meet a value the documentation does not list.

Types

type Cache

type Cache struct {
	// Dir is <data_dir>/media-cache.
	Dir string
	// Index is the single authority for what is in it.
	Index CacheIndex
	// MaxBytes is `media.cache_max_bytes`, 2 GiB by default.
	MaxBytes int64
}

Cache is the media cache on disk.

**It is a cache.** The bytes are always re-fetchable from Google, the budget is global across accounts rather than per account, and one account's backfill may evict another's cached media (spec section 10.3). Nothing here is a system of record.

func (*Cache) Evict

func (c *Cache) Evict(ctx context.Context) (freed int64, removed int, err error)

Evict brings the cache under its byte budget by removing the least-recently-used **unpinned** entries.

The order of the two removals is the erasure order of spec section 10.3, and it is the opposite of what looks natural: the ROW goes first, then the file. Deleting the file first and then failing to delete the row leaves the index claiming bytes that are not there; deleting the row first and then failing to unlink leaves a file nothing references, which an operator can delete. Only the second of those is recoverable.

func (*Cache) Get

func (c *Cache) Get(ctx context.Context, attachmentID string, nowMs int64) ([]byte, bool, error)

Get reads cached bytes and touches the entry. A row whose file has gone -- a partial restore, an operator's `rm` -- is treated as a miss and the row is dropped, so the index cannot go on claiming bytes that are not there.

func (*Cache) Pin

func (c *Cache) Pin(ctx context.Context, attachmentID string) error

Pin and Unpin guard an entry that is being read or that has an outstanding ticket, so the eviction sweep cannot delete it underneath itself.

func (*Cache) Put

func (c *Cache) Put(ctx context.Context, attachmentID string, data []byte, nowMs int64) (CacheEntry, error)

Put writes bytes into the cache and records the row.

The file is written to a temporary name and renamed into place, so a reader never sees a half-written file, and the row is written **after** the rename: a row pointing at a file that is not there yet would make the cache lie about what it holds, while a file with no row is merely an orphan an operator can delete.

func (*Cache) Resolve

func (c *Cache) Resolve(relative string) (string, error)

Resolve turns a stored relative path into an absolute one, refusing anything that escapes the cache directory.

func (*Cache) UnlinkAll

func (c *Cache) UnlinkAll(paths []string) []error

UnlinkAll removes files by relative path, after the transaction that deleted their rows has committed.

This is the second half of the erasure order (spec sections 4.7, 10.3): the paths are collected INSIDE the delete transaction, the transaction commits, and only then are the files unlinked. A crash between the commit and the unlink leaves a file nothing references, which an operator can delete; the other order would leave the eviction sweep unable to find a file it is responsible for, and the cache budget would silently stop matching the disk.

func (*Cache) Unpin

func (c *Cache) Unpin(ctx context.Context, attachmentID string) error

Unpin releases the guard.

type CacheEntry

type CacheEntry struct {
	AttachmentID string
	RelativePath string
	SizeBytes    int64
	// Pinned keeps an in-flight download or an open ticket from being
	// evicted underneath itself.
	Pinned     bool
	LastUsedMs int64
}

CacheEntry is one row of `media_cache_entries`, which is the **single authority for cached bytes on disk** (spec section 4.2). `attachments` carries no cache path and no cached size: the eviction sweep, the LRU order, the byte budget and the purge path all read this table and nothing else, so there is exactly one row per cached file and "no orphan row" is a well-defined assertion.

type CacheIndex

type CacheIndex interface {
	// Put records a cached file. It replaces any row for the same
	// attachment, because there is exactly one row per cached file.
	Put(ctx context.Context, e CacheEntry) error
	// Get reads one row.
	Get(ctx context.Context, attachmentID string) (CacheEntry, bool, error)
	// Touch updates last_used_ms. An LRU that did not is an MRU.
	Touch(ctx context.Context, attachmentID string, nowMs int64) error
	// SetPinned marks an entry unevictable while it is being read or while a
	// ticket for it is outstanding.
	SetPinned(ctx context.Context, attachmentID string, pinned bool) error
	// Unpinned lists evictable entries, oldest use first, with the total
	// bytes of every entry including the pinned ones -- the budget is a
	// budget for the whole cache, and a pinned entry still occupies disk.
	Unpinned(ctx context.Context) (entries []CacheEntry, totalBytes int64, err error)
	// Delete removes one row and returns its relative path, so the caller
	// unlinks the file only after the row is gone.
	Delete(ctx context.Context, attachmentID string) (relativePath string, err error)
}

CacheIndex is the persistence the cache needs. It is an interface so this package does not hold the store's write lock (spec section 2.2) and so the eviction order is testable without a database.

type Kind

type Kind string

Kind is which of the two ticket types a token is.

const (
	KindUpload   Kind = "upload"
	KindDownload Kind = "download"
)

func KindOf

func KindOf(value string) (Kind, bool)

KindOf reports which kind a presented value claims to be, so a redemption endpoint can refuse a download ticket presented at an upload URL without having to try both.

type Signer

type Signer struct {
	// contains filtered or unexported fields
}

Signer mints and verifies ticket values. The key is derived from AGENT_GM_DATA_KEY under `agent-gm/ticket/v1`, distinct from the session, attachment and cursor keys, so a ticket signature can never be produced by a key minted for something else (spec section 4.5).

func NewSigner

func NewSigner(dk store.DataKey) (*Signer, error)

NewSigner derives the ticket key.

func (*Signer) Mint

func (s *Signer) Mint(kind Kind, targetID string) (value string, hash string, err error)

Mint produces a fresh ticket value for one audience.

The value is `<prefix><nonce>.<mac>`, where the MAC covers the audience as well as the nonce. Only its SHA-256 hash is stored (section 10.3, section 12.1): the value leaves the process once and is never recoverable from the database, a log or an audit payload.

func (*Signer) Verify

func (s *Signer) Verify(value string, kind Kind, targetID string) (hash string, err error)

Verify checks a presented value against one audience and returns the hash to look the row up by.

The signature is checked with hmac.Equal -- crypto/subtle underneath -- over fixed-length MACs, never with `==` on strings (spec section 12.1). A presented value of the wrong shape is refused with exactly the same error as one with a bad MAC.

type StoreIndex

type StoreIndex struct{ Store *store.Store }

StoreIndex is the CacheIndex backed by `media_cache_entries`, which is the **single authority for cached bytes on disk** (spec section 4.2).

It exists because Cache is deliberately written against an interface rather than against the store: the eviction order, the LRU tiebreak and the erasure order are properties worth testing without a database, and internal/media must not hold the store's write lock (spec section 2.2). This is the one adapter that closes that seam in production.

The two methods with no counterpart on *store.Store -- Unpinned and Delete -- run through Store.Write and Store.Reader, which are the store's own exported handles. Nothing here interprets a row; it is transport between one table and one interface.

func NewStoreIndex

func NewStoreIndex(s *store.Store) *StoreIndex

NewStoreIndex builds the adapter.

func (*StoreIndex) Delete

func (i *StoreIndex) Delete(ctx context.Context, attachmentID string) (string, error)

Delete removes one row and returns its relative path.

The path is read **before** the delete and inside the same transaction, so the caller can unlink the file only after the row is gone. That order is the erasure order of spec section 10.3, and it is the opposite of what looks natural: deleting the file first and then failing to delete the row leaves the index claiming bytes that are not there, while deleting the row first and then failing to unlink leaves a file nothing references, which an operator can delete. Only the second is recoverable.

func (*StoreIndex) Get

func (i *StoreIndex) Get(ctx context.Context, attachmentID string) (CacheEntry, bool, error)

Get reads one row.

func (*StoreIndex) Put

func (i *StoreIndex) Put(ctx context.Context, e CacheEntry) error

Put records a cached file, replacing any row for the same attachment: there is exactly one row per cached file, which is what makes "no orphan row" a well-defined assertion.

func (*StoreIndex) SetPinned

func (i *StoreIndex) SetPinned(ctx context.Context, attachmentID string, pinned bool) error

SetPinned marks an entry unevictable while it is being read or while a ticket for it is outstanding.

func (*StoreIndex) Touch

func (i *StoreIndex) Touch(ctx context.Context, attachmentID string, _ int64) error

Touch moves an entry to the head of the LRU. An LRU that did not touch would be an MRU.

func (*StoreIndex) Unpinned

func (i *StoreIndex) Unpinned(ctx context.Context) ([]CacheEntry, int64, error)

Unpinned lists evictable entries oldest-use-first, with the total bytes of **every** entry including the pinned ones: the budget is a budget for the whole cache, and a pinned entry still occupies disk.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL