Keeping Files by Id

Blob Management has not been released yet; see the overview.

A business system that keeps a file library - attachments to a record, documents, media - stores its files in a managed container by id: Blob Management stores each file and returns it with an id, and the business system keeps that id (or, for a public file, its address) in its own data. These files share everything with the BLOBs an application stores by name: the same file descriptors, tenant allocation, de-duplication, upload rules and containers.

A file kept by id has a display name, which may repeat, and can be renamed, and moved between the directories of a container that has them. A file an application saved by name appears in the same listings and is read and deleted the same way, but is not renamed or moved (BlobManagement:FileAddressedByName).

What the Business System Does

Blob Management has no business rules, and authorizes no user for files. The business system:

  • builds the UI its users store, rename, move and delete files with;
  • applies its own rules - who may attach what to which record, who may see a file - before it calls;
  • calls as an application from its back end: in the same process as a trusted caller, or remotely as an OAuth client the container allows. That client's token reaches every tenant, so it never leaves the back end;
  • lets its browser in with what it asks Blob Management for on the user's behalf: an upload ticket to send a file, a read link to read one that is not public - or it receives the upload and hands the bytes on itself;
  • marks a file public when anyone may read it (Public Files).

A file's life is the life of the record that refers to it, and the business system decides it:

  • when it soft-deletes the record, it deletes the file (DeleteAsync(id)): the file is soft-deleted and keeps its bytes. It is not listed, not read by id, and its public address and read links answer 404;
  • when it restores the record, it restores the file (RestoreAsync(id)): the file is as it was, at the same address; at the top of its container if its directory was deleted meanwhile;
  • when it deletes the record for good, it deletes the file for good (DeleteAsync(id, permanently: true)), live or soft-deleted: the row, then its bytes.

Blob Management never deletes a file for good on its own, but one uploaded with a ticket and never confirmed. A file saved under a name (BLOB Storing Provider) is deleted for good at once: ABP's IBlobContainer cannot restore one. A soft-deleted file keeps counting against the tenant's allocation until it is deleted for good.

The File Service

IBlobManagementFileService, in Dignite.Abp.BlobManagement.Application.Contracts, works in the current tenant:

Method
GetAsync(id) One file's details - also of a file still pending.
GetListAsync(input) The files of the top of a container, or of one directory, a page at a time. Pending files are left out.
CreateAsync(input) Stores a file at the top of a container, or in a directory.
UpdateAsync(id, input) Renames it.
MoveAsync(id, input) Moves it to another directory of its container, or to the top.
SetPublicAsync(id, input) Marks it public or not (Public Files).
CreateUploadTicketAsync(input) An upload ticket for the browser.
ConfirmAsync(id) Confirms a file uploaded with a ticket.
CreateReadLinkAsync(id, input), CreateReadLinksAsync(input) Read links for the browser.
DeleteAsync(id) Deletes it. Deleting a file that is not there succeeds.
GetContentAsync(id) Its bytes, public or not.

The host decides which implementation answers, as for the provider:

  • In the same process: the host installs Dignite.Abp.BlobManagement.Application. The service is a trusted caller and checks no permission.
  • Remote: the host installs Dignite.Abp.BlobManagement.HttpApi.Client and its client-credentials configuration. The service calls the file API as the OAuth client, which must be granted the container's files (Granting an Application).
public class AttachmentManager : ITransientDependency
{
    private readonly IBlobManagementFileService _files;

    public AttachmentManager(IBlobManagementFileService files)
    {
        _files = files;
    }

    public async Task<Guid> AttachAsync(IRemoteStreamContent upload, Guid? directoryId)
    {
        // The business system's own rules have run before this.
        var file = await _files.CreateAsync(new CreateBlobManagementFileInput
        {
            ContainerName = "attachments",
            DirectoryId = directoryId,   // null: the top of the container
            File = upload                // its file name is the file's name unless Name is set
        });

        return file.Id;
    }
}

GetListAsync takes ContainerName, DirectoryId (none for the top of the container), Filter (a part of the name, whatever its case), Sorting (Name, Size, MimeType, CreationTime or LastModificationTime, then asc or desc; default Name asc; anything else is BlobManagement:SortingNotSupported) and ABP's paging. In a container without directories the same call, without DirectoryId, lists the whole container.

A file (BlobManagementFileDto) has its id, containerName, directoryId, name, isAddressedByName, mimeType (detected from the bytes), size, creatorId, clientId, isPublic, isPending, its creation and modification times, and url while it is public. mimeType and size are those of what is stored: in a container on the images preset a JPEG, and a PNG of 64 KB or more, is stored as WebP, and its name then ends in .webp. BlobManagementFileDto is extensible: what an application adds to it travels in extraProperties. A deleted file is kept as a deleted row.

The Uploader

CreatorId is the user a file is counted for in the usage figures, and nothing else: no right comes with it.

  • In the same process, it is the application's current user, as ABP's auditing records it.
  • Remotely, the client's token carries no user, so RemoteBlobManagementFileService - what Dignite.Abp.BlobManagement.HttpApi.Client registers - fills CreatorId with the application's current user. Blob Management believes it because it believes the client.
  • CreateBlobManagementFileInput.CreatorId names another user, when the application stores for someone else.
  • A file uploaded with a ticket is counted for the user the ticket was issued for.

A file stored over HTTP also records the client that stored it (clientId).

Verifying an Upload

A business system that holds the SHA-256 of a file can have the upload checked against it. Send the value as base64 of the 32 bytes - the spelling of RFC 9530's Content-Digest - and Blob Management compares it with the bytes that arrive, before anything is stored: a different one fails with BlobManagement:ChecksumMismatch (HTTP 400) and leaves no file, no BLOB and nothing counted. A value that is not base64 of 32 bytes is BlobManagement:ChecksumInvalid (400) too.

Way in Where the value goes
IBlobManagementFileService.CreateAsync and POST integration-api/blob-management/files Sha256 of the input; the form field sha256
IBlobManagementBlobService.SaveAsync and PUT integration-api/blob-management/blobs/{containerName} the sha256 argument; the query string sha256
POST api/blob-management/uploads/{ticket} (the browser) the form field sha256, or, when the body is the raw file, the header Content-Digest: sha-256=:<base64>:

The check is optional and costs nothing when it is not asked for: without a value no hash is computed, and the file's Hash is empty. With one, the hash is taken while the bytes are read in, so the upload does not wait for it afterwards. The value that was verified is kept as the file's hash, and the BLOB API's BlobManagementBlobDto.Hash returns it, exactly as it was sent. It is the hash of the bytes the business system sent, before the container's pipeline changed them - a JPEG stored as WebP still carries the hash of the JPEG.

A Content-Digest that names no sha-256 (for example only md5) is refused rather than ignored: the check it asked for cannot be made. A browser cannot hash a large file in a single call (SubtleCrypto.digest takes a whole buffer), so a direct upload from a browser sends a value for small files, or none.

A file stored through ABP's IBlobContainer is not checked: the BLOB storing provider has nowhere to carry the value. A business system that wants the check calls IBlobManagementBlobService itself, as Calling the BLOB Service Directly shows.

Picture Sizes

A business system can ask for a picture to be stored no larger than a box of its own - an avatar, a cover, a picture in an article - with ImageMaxWidth and ImageMaxHeight, in pixels:

Way in Where the box goes
IBlobManagementFileService.CreateAsync and POST integration-api/blob-management/files ImageMaxWidth and ImageMaxHeight of the input; the form fields imageMaxWidth and imageMaxHeight
CreateUploadTicketAsync ImageMaxWidth and ImageMaxHeight of the input, kept in the ticket

A picture larger than the box is scaled down to fit inside it, keeping its aspect ratio: it is never cropped and never enlarged. With a box of 1000 × 1000:

Uploaded Stored
4000 × 3000 1000 × 750
800 × 3000 267 × 1000
900 × 600 as uploaded
  • Either side can be left out (null): a box of width 1000 alone stores 4000 × 3000 as 1000 × 750.
  • The container's own box still applies, and each side is the smaller of the two: an upload can make what the container keeps smaller, never larger. In a container that resizes nothing, the upload's box is the only one; the picture is fitted after the container's own contributors and before its GZip compression, if it has one.
  • A container whose resize crops, stretches or pads (a Mode other than Max) takes no box: the upload, or the request for the ticket, fails with BlobManagement:ImageSizeNotSupported (HTTP 400).
  • The picture is scaled in the same step as the container's other processing: on the images preset, a JPEG is turned upright, fitted and stored as WebP in one encode.
  • What is not a picture is stored as it is, and so is a picture the image provider does not resize: on SkiaSharp, which Blob Management brings, anything but a JPEG, a PNG or a WebP, and an animated one.
  • A side that is not a positive number is a validation error. A BLOB saved under a name through ABP's IBlobContainer has no box of its own: it is the container's.

Public Files

Whether anyone may read a file at its public address, without signing in, is the business system's call, kept on the file (isPublic):

  • CreateBlobManagementFileInput.IsPublic marks a file when it is stored, and SetPublicAsync(id, new SetBlobManagementFilePublicInput { IsPublic = … }) changes it later.
  • A BLOB an application saves by name takes it from the application's container (Public Addresses), at each save; SetPublicAsync does not change it (BlobManagement:FileAddressedByName).

A public file has a url: /blobs/{container}/{blob}, with ?width=&height= for pictures (Public Addresses). For a file kept by id the address names the file's physical BLOB - 32 random hexadecimal digits and an extension - rather than its name, which need not be unique; renaming or moving the file leaves the address as it was.

Every file has a physical BLOB of its own, so an address is one file's, also when another file holds the same bytes: it answers while that file is public, and a download from it is named after that file. A file that is not public, or not confirmed yet, has no url, and its address answers 404. A cache that kept a response keeps it for up to a day after the file stops being public.

Upload Tickets

A ticket lets a browser send one file straight to Blob Management, without passing through the business system and without signing in to it. The business system asks for it on its back end, for its current user:

var ticket = await _files.CreateUploadTicketAsync(new CreateBlobManagementUploadTicketInput
{
    ContainerName = "attachments",
    DirectoryId = directoryId,                      // optional
    MaxSize = 10 * 1024 * 1024,                     // optional: at most the container's own limit
    AllowedContentTypes = { "application/pdf", "image/*" }, // optional: detected from the bytes
    ImageMaxWidth = 1920,                           // optional: see Picture Sizes
    LifetimeInSeconds = 300                         // optional
});
// ticket.UploadUrl: /api/blob-management/uploads/{ticket}
// ticket.FileId:    the id the file will have
  • The ticket is signed by Blob Management with ASP.NET Core Data Protection and carries the tenant, the container, the directory, the file's id, the user (UploaderId; by default the current user, which the remote service sends), the client, the size, the types and the box for pictures (Picture Sizes). The browser can change none of it.
  • The size and the types narrow the container's own rules, never widen them: the upload runs the container's contributors with the smaller size and the types both allow (image/* on the ticket and image/png, image/jpeg on the container take the two). A ticket whose types the container takes none of is refused when it is asked for (Dignite.Abp.BlobStoring:ContentTypeNotAllowed, HTTP 415); one that is not type/subtype or type/* is a validation error (HTTP 400).
  • Its lifetime is LifetimeInSeconds, else BlobManagementUploadOptions.TicketLifetime (5 minutes), and never more than MaxTicketLifetime (1 hour).
  • The browser posts the file to UploadUrl - relative to Blob Management's address - as the multipart field file (or the raw body, with ?name=). The request is anonymous: no token, cookie, antiforgery token or tenant header is needed or used. The body is limited to the ticket's size.
const form = new FormData();
form.append('file', input.files[0]);
const response = await fetch(blobManagementUrl + ticket.uploadUrl, { method: 'POST', body: form });
const file = await response.json(); // file.id === ticket.fileId, file.isPending === true

A ticket stores one file: the file takes the ticket's id, and a second upload is refused while that file exists, soft-deleted or not (BlobManagement:UploadTicketUsed, 409). Once the file is deleted for good, the ticket can store one again until it expires - pending, like the first. An expired or altered ticket is BlobManagement:UploadTicketInvalid (403). The container's own rules apply as for any file.

The file is pending until the business system confirms it: it is not listed, gets no read link and is not read publicly, but it counts in the usage and the allocation. When the browser reports the upload, the business system reads the file by its id, checks that creatorId is its current user (and whatever else it requires), files it with its record and confirms it:

var file = await _files.GetAsync(fileId);
if (!file.IsPending || file.CreatorId != CurrentUser.Id)
{
    throw new AbpAuthorizationException();
}

await _files.ConfirmAsync(fileId);

A file still pending after BlobManagementUploadOptions.PendingLifetime (24 hours) is deleted by a background worker that runs every CleanupPeriod (1 hour), in every tenant; with several instances, one of them at a time, under the distributed lock. A host that turns ABP's background workers off runs BlobManagementPendingFileCleaner.CleanAsync itself.

Configure<BlobManagementUploadOptions>(options =>
{
    options.TicketLifetime = TimeSpan.FromMinutes(10);
    options.PendingLifetime = TimeSpan.FromHours(6);
});

A read link lets a browser read a file that is not public, for a few minutes, straight from Blob Management. The business system asks for it once it has decided its user may see the file:

var link = await _files.CreateReadLinkAsync(fileId, new CreateBlobManagementReadLinkInput());
// link.Url: /api/blob-management/links/{link}, link.ExpirationTime

var page = await _files.CreateReadLinksAsync(new CreateBlobManagementReadLinksInput { Ids = fileIds });
  • A link names the tenant and the file, signed as a ticket is. Its lifetime is LifetimeInSeconds, else BlobManagementReadLinkOptions.LinkLifetime (10 minutes), never more than MaxLinkLifetime (1 hour).
  • The same file within one window is the same link: the expiration is rounded up to LinkWindow (5 minutes), and the link is kept in the distributed cache until then, so a browser's cache - keyed by the address - serves the file again rather than reading it anew. A cache that misses only costs a new link.
  • CreateReadLinksAsync takes up to 100 ids; a file that is not there, not the client's, or pending is left out of the result.
  • A pending file gets no link (BlobManagement:FilePending, 409).

The browser reads GET (or HEAD) /api/blob-management/links/{link} anonymously. The response is Cache-Control: private, for no longer than the link has left, with an ETag and a Last-Modified (conditional requests are answered 304), Range requests served as on a public read (Public Addresses), nosniff, and a type outside the module's list served as an attachment. An expired or altered link answers 403; a file deleted meanwhile, 404. A link is a credential: give it to the user it is for, and do not log it.

Configure<BlobManagementReadLinkOptions>(options =>
{
    options.LinkLifetime = TimeSpan.FromMinutes(30);
    options.LinkWindow = TimeSpan.FromMinutes(10);
});

The File API

The file service over HTTP is IBlobManagementFileIntegrationService, at integration-api/blob-management/files: an ABP integration service, for a business system's back end. It admits an OAuth client granted the files of the file's container, with a token that carries no user, and no one else. A file in a container the client is not granted is not found.

As any integration service, it is there only where the host exposes integration services (Blob Management as Its Own Service), and its calls are not audit-logged unless the host turns that on (AbpAuditingOptions.IsEnabledForIntegrationServices).

No user stores, renames, moves or deletes a file through the module, and no user gets a ticket or a link.

GET integration-api/blob-management/files?containerName=&directoryId= The files of a place, a page at a time.
GET integration-api/blob-management/files/{id} One file.
GET integration-api/blob-management/files/{id}/content Its bytes, always as an attachment - a file may be HTML, and is never rendered on the host's address.
POST integration-api/blob-management/files Stores a file: a form with containerName, an optional directoryId, name, creatorId, isPublic and sha256, and the file in file.
PUT integration-api/blob-management/files/{id} Renames it: name.
PUT integration-api/blob-management/files/{id}/move Moves it to directoryId of the same container; none for the top.
PUT integration-api/blob-management/files/{id}/public Marks it public or not: isPublic.
POST integration-api/blob-management/files/upload-tickets An upload ticket.
POST integration-api/blob-management/files/{id}/confirm Confirms a file uploaded with a ticket.
POST integration-api/blob-management/files/{id}/read-link, POST integration-api/blob-management/files/read-links Read links.
DELETE integration-api/blob-management/files/{id}?permanently= Deletes it: soft, or for good with permanently=true.
POST integration-api/blob-management/files/{id}/restore Restores a soft-deleted file.

What the Management Page Reads

A user who holds BlobManagement.Containers reads files through IBlobManagementFileAppService, at api/blob-management/files - what the management page reads with. It reads and changes nothing:

GET api/blob-management/files?containerName=&directoryId= The files of a place, a page at a time.
GET api/blob-management/files/{id} One file.
GET api/blob-management/files/{id}/content Its bytes, always as an attachment.

A token without a user - a client acting for itself - is refused here, as it is by the directory, container and usage APIs.

The browser's two addresses are not part of the API, and have no client proxy:

POST api/blob-management/uploads/{ticket} The upload with a ticket.
GET/HEAD api/blob-management/links/{link} The read with a link.

The Tenant Feature

The file, directory, container and usage services are part of the tenant's Blob Management: with the tenant's BlobManagement.Enable feature off, every call is refused (ABP's feature error, HTTP 403), and an upload with a ticket is refused too. Reads are not closed by it: a public file stays readable at its address, and a read link handed out stays readable until it expires, while nothing new can be stored.

Events

FileDescriptor publishes ABP's automatic distributed entity events (EntityCreatedEto<EntityEto> and the like), so another service learns about changes without Blob Management defining event types of its own.

Errors

A missing file is ABP's not found (404); a caller the file API does not admit, ABP's authorization error (403). The other errors are Blob Management's own (Setting Up, Directories) and those of the container's contributors, such as Dignite.Abp.BlobStoring:ContentTooLarge.

See Also