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
- Variables
- func AgentLine(name, contentType string, size int64, url string) string
- func CleanFilename(name string) string
- func Disposition(s Serving, name string) string
- func HumanSize(n int64) string
- func InlineImage(contentType string) bool
- func IsRefusal(err error) bool
- func NewPublicID() (string, error)
- func ObjectKeyFor(id string) string
- func SafeName(name string) string
- func SetServeHeaders(h http.Header, sniffedType, filename string, size int64)
- func Sniff(head []byte) string
- func ValidPublicID(id string) bool
- type LifecycleCoverage
- type ObjectStore
- type Opened
- type PGStore
- func (s *PGStore) Create(ctx context.Context, u Upload) (Upload, error)
- func (s *PGStore) Get(ctx context.Context, publicID string) (Upload, error)
- func (s *PGStore) LinkTarget(ctx context.Context, publicID string) (Upload, error)
- func (s *PGStore) Revoke(ctx context.Context, publicID string) (Upload, error)
- type Ref
- type S3
- func (c *S3) Check(ctx context.Context) error
- func (c *S3) Cleanup(ctx context.Context, key string) error
- func (c *S3) Delete(ctx context.Context, key string) error
- func (c *S3) Get(ctx context.Context, key string) (io.ReadCloser, int64, error)
- func (c *S3) Incomplete(ctx context.Context, prefix string) (int, error)
- func (c *S3) Lifecycle(ctx context.Context) (LifecycleCoverage, error)
- func (c *S3) Put(ctx context.Context, key string, r io.Reader, size int64, contentType string) error
- func (c *S3) Stat(ctx context.Context, key string) (int64, error)
- type S3Config
- type S3Error
- type Service
- func (s *Service) Describe(u Upload) Stored
- func (s *Service) Link(u Upload) string
- func (s *Service) OpenLink(ctx context.Context, publicID string, q url.Values) (Opened, error)
- func (s *Service) OpenOwned(ctx context.Context, publicID string) (Opened, error)
- func (s *Service) Put(ctx context.Context, r io.Reader, filename string) (Stored, error)
- func (s *Service) Revoke(ctx context.Context, publicID string) (objectErr, err error)
- func (s *Service) StatLink(ctx context.Context, publicID string, q url.Values) (Opened, error)
- type Serving
- type Signer
- type Store
- type Stored
- type Upload
Constants ¶
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.
const DefaultHeaderTimeout = 30 * time.Second
DefaultHeaderTimeout is how long the store has to start answering.
const DefaultRegion = "us-east-1"
DefaultRegion is the signing region when none is configured.
const DefaultWriteTimeout = 10 * time.Minute
DefaultWriteTimeout bounds one file's write to the store.
const LinkPath = "/f/"
LinkPath is the public route a signed link names: GET /f/{id}.
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.
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.
const SniffBytes = 512
SniffBytes is how much of a file Classify reads: http.DetectContentType's own window.
Variables ¶
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.
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.
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).
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 ¶
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 ¶
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 ¶
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 ¶
HumanSize is n bytes as a person reads it: "312 B", "312 KB", "4.2 MB". 1 KB is 1024 bytes.
func InlineImage ¶
InlineImage reports whether contentType is an image a page may show in an <img> (a thumbnail): the raster images of inlineTypes.
func IsRefusal ¶
IsRefusal reports whether err is one of the answers a link check gives (every one of them is a 404 to the caller).
func ObjectKeyFor ¶
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 ¶
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 ¶
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 ¶
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 ¶
ValidPublicID reports whether id is spelled like a public id.
Types ¶
type LifecycleCoverage ¶
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 ¶
func Coverage(cfg *lifecycle.Configuration) LifecycleCoverage
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 (*PGStore) LinkTarget ¶
LinkTarget reads one row by public id under the system principal.
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.
type S3 ¶
type S3 struct {
// contains filtered or unexported fields
}
S3 is ObjectStore over minio-go.
func (*S3) Incomplete ¶
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.
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 ¶
S3Error is a non-success answer from the store, naming its status and S3's code, never a credential.
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) OpenLink ¶
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 ¶
OpenOwned opens the caller's own upload (the owner's preview), until it is revoked.
func (*Service) Put ¶
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 ¶
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.
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 ¶
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 ¶
NewSigner returns a Signer over key, which must be at least MinSigningKeyBytes long.
func (Signer) Sign ¶
Sign is the link signature for public id id, valid until exp (Unix seconds): 43 characters of unpadded base64url.
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.
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. |