uploads

package
v0.190.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 27 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 uploads is the message composer's file attachments (migration 0024): a file the operator attaches is stored in an S3-compatible object store (e.g. MinIO), and the agent it is sent to is handed a SHORT-LIVED, muster-SIGNED link to it on muster's public URL — never the object store's own address, which is LAN-only.

composer ──POST /uploads──▶ muster ──PUT──▶ object store (bucket, random key)
agent ──GET <public>/f/<id>?exp=…&sig=…──▶ muster ──GET──▶ object store

🔴 THE LINK IS MUSTER'S, AND MUSTER STREAMS THE BYTES. The signature is an HMAC under a key only this server holds (MUSTER_UPLOAD_SIGNING_KEY), over the upload's public id and the link's expiry. GET /f/{id} checks the signature, the expiry, and the row — a REVOKED upload answers 404 even inside its expiry — before a byte is read from the store. So a link works from any host, on or off the LAN, and is both expiring and revocable.

🔴 NOTHING THE CLIENT SAYS ABOUT THE FILE DECIDES HOW IT IS SERVED. The type is SNIFFED from the bytes (Classify); the original filename is stored for the owner's eyes and never reaches the object key (NewPublicID is random), and what an agent or a Content-Disposition header sees is SafeName's reduction of it. Only PNG, JPEG, GIF and WebP are served inline; a PDF is a labelled attachment; HTML, SVG, XML, script and anything unrecognised is an attachment typed application/octet-stream. SetServeHeaders is the one place the response headers are decided.

Index

Constants

View Source
const (
	// DefaultMaxBytes caps one file (MUSTER_UPLOAD_MAX_BYTES).
	DefaultMaxBytes int64 = 25 << 20
	// MaxMaxBytes is the most MUSTER_UPLOAD_MAX_BYTES may say. A file is
	// STREAMED to the store (at most about two PartSize buffers held at once),
	// so this bounds the bucket, not memory.
	MaxMaxBytes int64 = 100 << 20
	// DefaultLinkTTL is how long a link works (MUSTER_UPLOAD_LINK_TTL).
	DefaultLinkTTL = 24 * time.Hour
	// MinLinkTTL and MaxLinkTTL bound MUSTER_UPLOAD_LINK_TTL.
	MinLinkTTL = time.Minute
	MaxLinkTTL = 7 * 24 * time.Hour
)

Defaults and bounds of the deployment's knobs.

View Source
const DefaultHeaderTimeout = 30 * time.Second

DefaultHeaderTimeout is how long the store has to start answering.

View Source
const DefaultRegion = "us-east-1"

DefaultRegion is the signing region when none is configured.

View Source
const DefaultWriteTimeout = 10 * time.Minute

DefaultWriteTimeout bounds one file's write to the store.

View Source
const LinkPath = "/f/"

LinkPath is the public route a signed link names: GET /f/{id}.

View Source
const MinSigningKeyBytes = 32

MinSigningKeyBytes is the shortest signing key accepted. A link's whole strength is this key's: 32 bytes is HMAC-SHA256's own block of security.

View Source
const PartSize = 5 << 20

PartSize is the size of each part of a streamed upload, and so about the most one upload holds in memory at once: minio-go buffers one part, and Service.Put buffers one more while it decides whether the file fits in a single request.

View Source
const SniffBytes = 512

SniffBytes is how much of a file Classify reads: http.DetectContentType's own window.

Variables

View Source
var (
	ErrBadLink     = errors.New("uploads: malformed link")
	ErrBadSig      = errors.New("uploads: link signature does not match")
	ErrLinkExpired = errors.New("uploads: link has expired")
)

Errors Verify answers. A handler answers every one of them identically (404), so a caller cannot learn which check failed; they are distinct for tests and the log.

View Source
var (
	// ErrNotFound is an upload that does not exist or is not the caller's —
	// the two answer identically.
	ErrNotFound = errors.New("uploads: no such upload")
	// ErrTooLarge is a file over the configured cap.
	ErrTooLarge = errors.New("uploads: file is too large")
	// ErrEmpty is a file with no bytes.
	ErrEmpty = errors.New("uploads: file is empty")
)

Errors a caller branches on.

View Source
var ErrLifecycleUnreadable = errors.New("uploads: the bucket's lifecycle configuration cannot be read with this credential")

ErrLifecycleUnreadable is a lifecycle configuration the credential may not read (s3:GetLifecycleConfiguration is not granted).

View Source
var ErrTruncated = errors.New("uploads: the file did not arrive whole")

ErrTruncated is a file whose body ended before its multipart boundary: the client went away mid-upload.

Functions

func AgentLine

func AgentLine(name, contentType string, size int64, url string) string

AgentLine is the text an attached file adds to the message the agent receives: short, and enough to fetch the file with one command.

[attached: shot.png (image/png, 312 KB) <url> — download with curl -sSfo shot.png '<url>']

name must already be a SafeName; url is a signed link (Signer.URL), whose alphabet holds no quote.

func CleanFilename

func CleanFilename(name string) string

CleanFilename is the browser's filename as stored: its last path element, control and format characters removed, invalid UTF-8 dropped, capped at 255 bytes. "" becomes "file".

func Disposition

func Disposition(s Serving, name string) string

Disposition is the Content-Disposition for a file named name served as s: `inline` or `attachment`, with the SafeName as the ASCII `filename=` and, when that lost anything, the original name (CleanFilename) as an RFC 5987 `filename*=UTF-8”…`, which every current browser prefers.

🔴 THE ENCODED VALUE IS PERCENT-ENCODED BYTE BY BYTE: only RFC 5987 attr-chars pass through, so no quote, backslash, `;`, space, CR or LF from a name can reach the header. The stored name is capped (CleanFilename), so the value is at most 3×255 bytes.

func HumanSize

func HumanSize(n int64) string

HumanSize is n bytes as a person reads it: "312 B", "312 KB", "4.2 MB". 1 KB is 1024 bytes.

func InlineImage

func InlineImage(contentType string) bool

InlineImage reports whether contentType is an image a page may show in an <img> (a thumbnail): the raster images of inlineTypes.

func IsRefusal

func IsRefusal(err error) bool

IsRefusal reports whether err is one of the answers a link check gives (every one of them is a 404 to the caller).

func NewPublicID

func NewPublicID() (string, error)

NewPublicID mints a random public id.

func ObjectKeyFor

func ObjectKeyFor(id string) string

ObjectKeyFor is the object key of the upload with public id id.

🔴 THE KEY IS THE RANDOM ID AND NOTHING ELSE. No filename, no owner, no type: a name the browser chose never becomes part of a path anywhere.

func SafeName

func SafeName(name string) string

SafeName is a filename reduced to what is safe to put anywhere an agent or a shell will read it: [A-Za-z0-9._-] only (every other run becomes one "_"), never starting with "." or "-" (a hidden file, a flag), capped at 80 characters with the extension kept. "" becomes "file"; a stem with nothing left in it becomes "file" ahead of its extension ("報告.pdf" → "file.pdf").

🔴 IT IS WHAT MAKES THE curl LINE SAFE TO PASTE. The name is written unquoted after `-o` in the line the agent is handed (AgentLine); a name that could hold a quote, a space, a `$` or a leading dash would turn a download into something else.

func SetServeHeaders

func SetServeHeaders(h http.Header, sniffedType, filename string, size int64)

SetServeHeaders sets every header that makes a served file inert, for a file whose SNIFFED type (Sniff, never a client's claim) is sniffedType. It is the ONE place these headers are decided: every route that serves bytes someone uploaded — the signed link, the owner's view, a task's attachment — calls it, so they cannot drift. size < 0 sets no Content-Length.

It overwrites (Set, never Add) whatever an earlier middleware put there, the app's own page CSP included: that one allows inline script.

func Sniff

func Sniff(head []byte) string

Sniff is the content type of a file whose first bytes are head, read from the bytes alone (http.DetectContentType). The client's Content-Type and the filename's extension are never consulted.

func ValidPublicID

func ValidPublicID(id string) bool

ValidPublicID reports whether id is spelled like a public id.

Types

type LifecycleCoverage

type LifecycleCoverage struct {
	Expire          int
	AbortIncomplete int
}

LifecycleCoverage counts the enabled lifecycle rules covering uploads/: those that EXPIRE objects (an expired link's file), and those that ABORT incomplete multipart uploads (a failed stream's parts).

func Coverage

Coverage counts cfg's enabled rules whose prefix (none, or one the uploads/ keys start with) covers the uploads/ objects: those with an expiration, and those that abort incomplete multipart uploads.

type ObjectStore

type ObjectStore interface {
	// Put stores r at key. size is r's length, or -1 when unknown (the file is
	// then streamed in parts). A read error from r aborts the write.
	Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
	// Get opens key. The caller closes the body. A missing key is ErrNotFound.
	Get(ctx context.Context, key string) (body io.ReadCloser, size int64, err error)
	// Stat is key's size, without its body. A missing key is ErrNotFound.
	Stat(ctx context.Context, key string) (size int64, err error)
	Delete(ctx context.Context, key string) error
	// Cleanup removes whatever a failed Put left at key: any incomplete
	// multipart upload (aborted) and any object.
	Cleanup(ctx context.Context, key string) error
	// Check reaches the bucket with the configured credential.
	Check(ctx context.Context) error
	// Lifecycle reports which of the bucket's enabled lifecycle rules cover
	// the uploads/ prefix. ErrLifecycleUnreadable when the credential may not
	// read the configuration.
	Lifecycle(ctx context.Context) (LifecycleCoverage, error)
}

ObjectStore is what the upload service needs of a bucket.

type Opened

type Opened struct {
	Upload
	// Body is nil for a Stat (a HEAD).
	Body io.ReadCloser
	// Size is the object's length as the store reports it.
	Size int64
}

Opened is a file ready to stream.

type PGStore

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

PGStore is Store on Postgres.

func NewPG

func NewPG(pool *pgxpool.Pool) *PGStore

NewPG returns a Store on pool.

func (*PGStore) Create

func (s *PGStore) Create(ctx context.Context, u Upload) (Upload, error)

Create inserts u (its ID, OwnerID, CreatedAt and RevokedAt are ignored).

func (*PGStore) Get

func (s *PGStore) Get(ctx context.Context, publicID string) (Upload, error)

Get is the caller's upload by public id.

func (*PGStore) LinkTarget

func (s *PGStore) LinkTarget(ctx context.Context, publicID string) (Upload, error)

LinkTarget reads one row by public id under the system principal.

func (*PGStore) Revoke

func (s *PGStore) Revoke(ctx context.Context, publicID string) (Upload, error)

Revoke marks the caller's upload revoked (first revocation's time kept).

type Ref

type Ref struct {
	// Start and End are its byte offsets in the message.
	Start, End  int
	Name        string
	ContentType string
	Size        string
	URL         string
	PublicID    string
}

Ref is one AgentLine found in a message.

func FindRefs

func FindRefs(text string) []Ref

FindRefs is every AgentLine in text, in order.

func (Ref) IsImage

func (r Ref) IsImage() bool

IsImage reports whether the attachment is an image a preview can show.

type S3

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

S3 is ObjectStore over minio-go.

func NewS3

func NewS3(cfg S3Config) (*S3, error)

NewS3 validates cfg and returns a client.

func (*S3) Check

func (c *S3) Check(ctx context.Context) error

Check is HEAD on the bucket.

func (*S3) Cleanup

func (c *S3) Cleanup(ctx context.Context, key string) error

Cleanup aborts every incomplete multipart upload of key and deletes key.

func (*S3) Delete

func (c *S3) Delete(ctx context.Context, key string) error

Delete removes key. A key already gone is not an error.

func (*S3) Get

func (c *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error)

Get opens key: the GET is made, and its status known, before this returns.

func (*S3) Incomplete

func (c *S3) Incomplete(ctx context.Context, prefix string) (int, error)

Incomplete counts the incomplete multipart uploads under prefix.

func (*S3) Lifecycle

func (c *S3) Lifecycle(ctx context.Context) (LifecycleCoverage, error)

Lifecycle reads the bucket's lifecycle and counts the enabled rules that cover the uploads/ prefix, by action.

func (*S3) Put

func (c *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error

Put stores r at key: one request when size is known and within a part, otherwise a multipart upload in PartSize pieces (aborted on a read error).

func (*S3) Stat

func (c *S3) Stat(ctx context.Context, key string) (int64, error)

Stat is HEAD on key.

type S3Config

type S3Config struct {
	// Endpoint is the server's base URL, http(s)://host[:port], no path.
	Endpoint  string
	Bucket    string
	AccessKey string
	SecretKey string
	// Region is the signing region; MinIO's default is us-east-1.
	Region string
	// HeaderTimeout bounds the wait for a response's headers; 0 is
	// DefaultHeaderTimeout. Nothing bounds a body but its context.
	HeaderTimeout time.Duration
}

S3Config is an S3-compatible endpoint, bucket and credential.

type S3Error

type S3Error struct {
	Op     string
	Status int
	Code   string
}

S3Error is a non-success answer from the store, naming its status and S3's code, never a credential.

func (*S3Error) Error

func (e *S3Error) Error() string

type Service

type Service struct {
	Store   Store
	Objects ObjectStore
	Signer  Signer
	// PublicURL is MUSTER_PUBLIC_URL: the base every link is written on.
	PublicURL string
	MaxBytes  int64
	LinkTTL   time.Duration
	// WriteTimeout bounds one file's write to the store; 0 is
	// DefaultWriteTimeout.
	WriteTimeout time.Duration
	Logger       *log.Logger
	// Now is the clock; nil is time.Now.
	Now func() time.Time
}

Service is the upload feature: a store of rows, a bucket of bytes, and the key links are signed with. A nil *Service is "feature off".

func (*Service) Describe

func (s *Service) Describe(u Upload) Stored

Describe is u as the composer is told about it.

func (s *Service) Link(u Upload) string

Link is the signed URL for u (its own expiry).

func (s *Service) OpenLink(ctx context.Context, publicID string, q url.Values) (Opened, error)

OpenLink checks a signed link and opens the file. Every refusal is ErrNotFound, ErrBadLink, ErrBadSig or ErrLinkExpired; the handler answers them all alike.

func (*Service) OpenOwned

func (s *Service) OpenOwned(ctx context.Context, publicID string) (Opened, error)

OpenOwned opens the caller's own upload (the owner's preview), until it is revoked.

func (*Service) Put

func (s *Service) Put(ctx context.Context, r io.Reader, filename string) (Stored, error)

Put stores one file, read from r, under the caller's principal (the row's owner). filename is the browser's name for it.

🔴 THE FILE IS STREAMED, NEVER HELD WHOLE. Its type is sniffed from the first SniffBytes; then up to one PartSize is read. A file that ends within it is written in one request of known size; a longer one is written as a multipart stream (size -1), so at most about two parts are in memory whatever MaxBytes says. One byte over MaxBytes fails the read the store is consuming, which aborts the write: ErrTooLarge, and nothing is stored.

The object is written FIRST and the row second; a row that cannot be written takes its object away again.

🔴 THE STORE IS WRITTEN UNDER ITS OWN CONTEXT, NOT THE REQUEST'S. Go cancels a request's context when its client goes away (and the handler's read can fail first, on a disconnect or the read deadline). A multipart write cancelled that way cannot send its own AbortMultipartUpload — the abort rides the same dead context — and the parts already written stay in the bucket, orphaned. So the write runs under context.WithoutCancel with its own bound (WriteTimeout); it still ends when the BODY fails, because the body is what it reads. And every failed write is cleaned up explicitly (abort any incomplete upload, delete any object) under a fresh bounded context.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, publicID string) (objectErr, err error)

Revoke ends the caller's upload's link: the row is marked revoked (so the link answers 404 at once) and the object is deleted. err is a failure to revoke (ErrNotFound for an upload that is not the caller's); objectErr, with err nil, is a revocation that HAPPENED whose object could not be deleted — the link is dead either way, and the bytes outlive it until the bucket's lifecycle rule takes them.

func (s *Service) StatLink(ctx context.Context, publicID string, q url.Values) (Opened, error)

StatLink checks a signed link exactly as OpenLink does and reports the file's size WITHOUT fetching its body (a HEAD).

type Serving

type Serving struct {
	// ContentType is the response's Content-Type.
	ContentType string
	// Inline is true only for inlineTypes; everything else is an attachment.
	Inline bool
}

Serving is how a stored file goes out over HTTP.

func ServeAs

func ServeAs(contentType string) Serving

ServeAs is how a file whose sniffed type is contentType is served.

🔴 HTML, SVG AND XML ARE NEVER INLINE AND NEVER CARRY THEIR OWN TYPE. A file served inline as text/html (or image/svg+xml) from muster's origin is a stored XSS: its script runs as muster. The response also carries `X-Content-Type-Options: nosniff` and a sandboxing CSP (SetServeHeaders), so a browser does not second-guess the type given here.

type Signer

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

Signer mints and checks the muster-signed links GET /f/{id} serves.

func NewSigner

func NewSigner(key string) (Signer, error)

NewSigner returns a Signer over key, which must be at least MinSigningKeyBytes long.

func (Signer) Sign

func (s Signer) Sign(id string, exp int64) string

Sign is the link signature for public id id, valid until exp (Unix seconds): 43 characters of unpadded base64url.

func (Signer) URL

func (s Signer) URL(base, id string, exp time.Time) string

URL is the signed link to id on base (MUSTER_PUBLIC_URL), valid until exp.

func (Signer) Verify

func (s Signer) Verify(id string, q url.Values, now time.Time) error

Verify checks a link's id, its exp and sig query values against now.

🔴 THE SIGNATURE IS COMPARED IN CONSTANT TIME (hmac.Equal), and it is checked BEFORE the expiry is believed: an exp is only a number until the MAC over it matches.

type Store

type Store interface {
	Create(ctx context.Context, u Upload) (Upload, error)
	// Get is the caller's upload by public id; ErrNotFound otherwise.
	Get(ctx context.Context, publicID string) (Upload, error)
	// Revoke marks the caller's upload revoked and returns it (its object key
	// is then deleted by the caller). Revoking twice is not an error.
	Revoke(ctx context.Context, publicID string) (Upload, error)
	// LinkTarget is the upload a signed link names, read with NO principal:
	// the link's signature has already been checked, and it is how the
	// request learns anything at all. Only what serving needs is handed on.
	LinkTarget(ctx context.Context, publicID string) (Upload, error)
}

Store is the uploads table (migration 0024).

🔴 EVERY METHOD BUT LinkTarget RUNS UNDER THE CALLER'S PRINCIPAL. The table is under FORCE row-level security, so a request creates, reads and revokes only its own user's rows, and the owner of a new row is the principal's user (owner_id's default), never a parameter.

type Stored

type Stored struct {
	Upload
	// Name is the SafeName the agent sees.
	Name string
	// URL is the signed link.
	URL string
	// Line is the text the message carries (AgentLine).
	Line string
}

Stored is an upload as the composer is told about it.

type Upload

type Upload struct {
	ID       int64
	OwnerID  int64
	PublicID string
	// ObjectKey is where the bytes are in the bucket: ObjectKeyFor(PublicID).
	ObjectKey string
	// Filename is the name the browser gave, cleaned of control characters and
	// capped (CleanFilename). Shown to the OWNER only; agents see SafeName.
	Filename string
	// ContentType is the type sniffed from the bytes (Classify), never the
	// client's.
	ContentType string
	Size        int64
	CreatedAt   time.Time
	// ExpiresAt is when the link minted at upload stops working.
	ExpiresAt time.Time
	// RevokedAt is set when the owner revoked the link; nil while it works.
	RevokedAt *time.Time
}

Upload is one stored file's metadata row.

func (Upload) Revoked

func (u Upload) Revoked() bool

Revoked reports whether the owner revoked the upload's link.

Directories

Path Synopsis
Package uploadstest is in-memory fakes of internal/uploads' two ports — the row store and the object store — for tests that drive the upload routes without Postgres or an S3 server.
Package uploadstest is in-memory fakes of internal/uploads' two ports — the row store and the object store — for tests that drive the upload routes without Postgres or an S3 server.

Jump to

Keyboard shortcuts

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