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
4 changes: 4 additions & 0 deletions FullstackTemplate.Bff/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@
builder.AddBffSessions();
builder.Services.AddBffAuthentication(builder.Configuration, builder.Environment);
builder.Services.AddHttpForwarder();
builder.Services.AddOptions<ProxyOptions>()
.BindConfiguration(ProxyOptions.SectionName)
.ValidateDataAnnotations()
.ValidateOnStart();
// After AddHttpForwarder, which registers the default factory. The wrapper adds the DPoP nonce retry.
builder.Services.AddSingleton<IForwarderHttpClientFactory, DPoPProxy.NonceRetryClientFactory>();
// Bff:PublicOrigin, the forwarded headers, and the host filter
Expand Down
19 changes: 16 additions & 3 deletions FullstackTemplate.Bff/Proxy/ApiProxy.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
using FullstackTemplate.Bff.Authentication;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Http.Metadata;
using Microsoft.Extensions.Options;
using Microsoft.Extensions.Primitives;
using Microsoft.Net.Http.Headers;
using Serilog;
Expand All @@ -24,8 +26,11 @@ public static class ApiProxy

private static readonly ILogger Logger = Log.ForContext(typeof(ApiProxy));

private static Dictionary<string, TimeSpan> ActivityTimeoutsByContentType(ProxyOptions options) =>
new() { ["multipart/form-data"] = options.UploadActivityTimeout };

/// <summary>
/// Maps the forwarder. <paramref name="apiBaseUrl"/> ends with <c>/api</c>, because the forwarder strips the
/// Maps the forwarders. <paramref name="apiBaseUrl"/> ends with <c>/api</c>, because the forwarder strips the
/// local prefix: <c>/api/v1/x</c> goes to <c>&lt;server&gt;/api/v1/x</c>.
/// <para>
/// The request transforms: remove <c>Cookie</c>, remove <c>Authorization</c> and <c>DPoP</c> (the BFF is the only
Expand All @@ -35,8 +40,16 @@ public static class ApiProxy
/// <c>-Prefix</c> are set, <c>Forwarded</c> is removed, and the other response headers go back as they are.
/// </para>
/// </summary>
public static IEndpointConventionBuilder MapApiProxy(this IEndpointRouteBuilder endpoints, Uri apiBaseUrl) =>
endpoints.MapForwarder($"{Prefix}/{{**catch-all}}", apiBaseUrl.ToString(), ForwarderRequestConfig.Empty, transforms =>
public static void MapApiProxy(this IEndpointRouteBuilder endpoints, Uri apiBaseUrl)
{
var options = endpoints.ServiceProvider.GetRequiredService<IOptions<ProxyOptions>>().Value;
endpoints.MapApiForwarder(apiBaseUrl, options.ActivityTimeout);
foreach (var (contentType, activityTimeout) in ActivityTimeoutsByContentType(options))
endpoints.MapApiForwarder(apiBaseUrl, activityTimeout).WithMetadata(new AcceptsMetadata([contentType]));
}

private static IEndpointConventionBuilder MapApiForwarder(this IEndpointRouteBuilder endpoints, Uri apiBaseUrl, TimeSpan activityTimeout) =>
endpoints.MapForwarder($"{Prefix}/{{**catch-all}}", apiBaseUrl.ToString(), new ForwarderRequestConfig { ActivityTimeout = activityTimeout }, transforms =>
{
transforms.AddRequestHeaderRemove(HeaderNames.Cookie);
transforms.AddRequestHeaderRemove(HeaderNames.Authorization);
Expand Down
21 changes: 21 additions & 0 deletions FullstackTemplate.Bff/Proxy/ProxyOptions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
using System.ComponentModel.DataAnnotations;

namespace FullstackTemplate.Bff.Proxy;

public sealed class ProxyOptions
{
public const string SectionName = "Bff:Proxy";

/// <summary>
/// <c>Bff:Proxy:ActivityTimeout</c>. The longest time that a forwarded request waits with no progress, such as for
/// the answer of a hung Server. A request that reaches it gets a 504.
/// </summary>
[Range(typeof(TimeSpan), "00:00:01", "01:00:00")]
public TimeSpan ActivityTimeout { get; set; } = TimeSpan.FromSeconds(30);

/// <summary>
/// <c>Bff:Proxy:UploadActivityTimeout</c>. The same limit for an upload, a request with a multipart form.
/// </summary>
[Range(typeof(TimeSpan), "00:00:01", "01:00:00")]
public TimeSpan UploadActivityTimeout { get; set; } = TimeSpan.FromMinutes(5);
}
4 changes: 4 additions & 0 deletions FullstackTemplate.Bff/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@
"Refresh": {
"LockTimeout": "00:00:10",
"TokenRequestTimeout": "00:00:05"
},
"Proxy": {
"ActivityTimeout": "00:00:30",
"UploadActivityTimeout": "00:05:00"
}
}
}
9 changes: 9 additions & 0 deletions docs/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@ The design is in [docs/specs/home-rolled-bff.md](specs/home-rolled-bff.md). The
| `/api/{**catch-all}` | any | yes | The proxy to the server |
| `/health`, `/alive` | GET | no | The health checks |

### Time limits

| Setting | Default | Content |
|---|---|---|
| `Bff:Proxy:ActivityTimeout` | 30 seconds | The longest time that a request to `/api` waits with no progress, such as for the answer of a hung Server. The request then gets a 504. |
| `Bff:Proxy:UploadActivityTimeout` | 5 minutes | The same limit for a request with a multipart form, such as an upload. The Server stores the file after the last byte arrives, so the answer can take minutes. |

`ActivityTimeoutsByContentType` in `Proxy/ApiProxy.cs` maps each content type to its setting, and each content type gets its own forwarder. The SPA stops its own wait after 35 seconds, and after 10 minutes for an upload (`requestTimeoutMs` and `uploadTimeoutMs` in `frontend/src/lib/api-client.ts`). So the 504 of the BFF normally comes first, and a dropped network does not keep a page pending with no end. Either stop ends only the wait: the Server can still complete the request.

## Login flow

1. The React app calls `/bff/user` before it shows a page. Each page needs a session. If the answer is 204, the app shows no page and goes to the login.
Expand Down
9 changes: 6 additions & 3 deletions docs/backend/attachments.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ For the bucket in each environment, see [Object storage](../backend.md#object-st
| [`AttachmentStorage`](../../FullstackTemplate.Server/Domain/Attachments/AttachmentStorage.cs) | The add and the delete, in the order of [The order of the writes](#the-order-of-the-writes) |
| [`AttachmentMapper`](../../FullstackTemplate.Server/Domain/Attachments/Mappings/AttachmentMapper.cs) | The `AttachmentDto` with signed URLs, and the `AttachmentListDto` with the upload rules |
| [`MapStoredFile`](../../FullstackTemplate.Server/Databases/EntityConfigurations/StoredFileMapping.cs) | The columns `file_name`, `media_type`, `size_bytes`, and `storage_key` |
| [`AttachmentsSection`](../../frontend/src/components/attachments/attachments-section.tsx) | The Files section of a page: the heading, the hint, the upload button, the list, and the delete |
| [`AttachmentsSection`](../../frontend/src/components/attachments/attachments-section.tsx) | The Files section of a page: the heading, the hint, the upload button, the Cancel upload button, the list, and the delete |
| [`refreshBeforeUrlsExpire`](../../frontend/src/lib/attachment-list-refresh.ts) | The query options that load the list again before its URLs expire |

## Add attachments to an entity
Expand Down Expand Up @@ -176,7 +176,7 @@ The steps use a `Repair` that keeps photos. The code is in [AttachmentExampleTes

### In the SPA

1. **The hooks.** Write the list query with `refreshBeforeUrlsExpire`. The upload and the delete invalidate the list. The delete invalidates it also after a refusal, because another user can have deleted the file.
1. **The hooks.** Write the list query with `refreshBeforeUrlsExpire`. The upload and the delete invalidate the list. The delete invalidates it also after a refusal, because another user can have deleted the file. The upload takes an `Upload` from `components/attachments/types.ts` and gives its `signal` to the client, so that the Cancel button of the section can stop it.

```ts
export const repairPhotosQueryOptions = (repairId: string) =>
Expand All @@ -185,9 +185,11 @@ The steps use a `Repair` that keeps photos. The code is in [AttachmentExampleTes
queryFn: ({ signal }) => getRepairPhotos({ path: { id: repairId }, signal }),
...refreshBeforeUrlsExpire,
})

mutationFn: ({ file, signal }: Upload) => addRepairPhoto({ path: { id: repairId }, body: { file }, signal }),
```

2. **The section.** Give `AttachmentsSection` the three hooks. It shows the hint, such as "PNG, JPEG, or WebP. Up to 5 MB.", and it lets the file chooser offer only the types of the rules. It shows the toasts and moves the focus after a delete.
2. **The section.** Give `AttachmentsSection` the three hooks. It shows the hint, such as "PNG, JPEG, or WebP. Up to 5 MB.", and it lets the file chooser offer only the types of the rules. It shows the toasts and moves the focus after a delete. While an upload is on the way, it shows a Cancel upload button. A cancel stops the request and shows no message.

```tsx
<AttachmentsSection
Expand Down Expand Up @@ -281,6 +283,7 @@ A requeue is safe, because a delete of an object that is gone succeeds.
- The objects of a dead job stay until a person requeues the job. No alert or health check shows a dead job.
- An add whose save fails deletes its object at once, and does not use a job. If that delete fails, the object stays until the tenant delete.
- A URL stops before `urlsExpireAt` when the credentials that signed it expire. See [Presigned URLs](#presigned-urls).
- A cancel or a time limit stops the wait of the SPA, not the work of the Server. If all the bytes arrived, the Server can still store the file, and a second try then adds a second file. The list shows it at its next load.

<!-- example:start -->
## The example
Expand Down
2 changes: 1 addition & 1 deletion docs/frontend.md
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ Wrap the `cva` call of a `*-variants.ts` file in `withMergedClasses` from `@/lib
- `withCredentials: true` sends the BFF cookie.
- The `X-CSRF: 1` header is necessary for the BFF CSRF protection.
- An error response that has problem details becomes a `ProblemDetailsError`. The client shows it as a toast by default. To stop the toast, send `{ suppressErrorToast: true }` with the request.
- The `message` of each error that the client throws is the text for the user, so a toast, a form, and a page show the same text. A refusal (a 4xx problem) gives the `detail` of the Server, or its `title`. A 5xx, an answer with no problem details, and a request with no answer give the text of the SPA in `lib/problem-details.ts`. See [In the SPA](messages.md#in-the-spa).
- The `message` of each error that the client throws is the text for the user, so a toast, a form, and a page show the same text. A refusal (a 4xx problem) gives the `detail` of the Server, or its `title`. A 5xx, an answer with no problem details, a request that reaches its time limit, and a request with no answer give the text of the SPA in `lib/problem-details.ts`. See [In the SPA](messages.md#in-the-spa).

The generated API clients send each request through `apiClient`. `main.tsx` imports `lib/api-client.ts` to connect them before the first request. Use `apiClient` directly only for endpoints that are not in the OpenAPI document, such as `/bff/user`.

Expand Down
2 changes: 1 addition & 1 deletion docs/messages.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,4 +72,4 @@ The text of an MCP tool error starts with a code such as `permission_denied`, so

## In the SPA

`apiClient` shows the `detail` of a problem in a toast (see [API client](frontend.md#api-client)). It shows the text of the Server only for a refusal, a 4xx. A 5xx has no text for a user: its `title` is the default of ASP.NET, and a `detail` is for a developer. So for a 5xx, and for an answer that is not a problem, the SPA shows `serverFaultMessage` of `lib/problem-details.ts`. For a request with no answer, it shows `noAnswerMessage`. The `message` of the error has the same text, so a form or a page that shows the error shows no text of the Server. A component that also shows the error must not repeat the same text. When the SPA writes its own text, such as a toast, a label, or an empty state, these rules also apply. The SPA has no check for them. The `verify-fullstack-template` skill reads each message on the screen.
`apiClient` shows the `detail` of a problem in a toast (see [API client](frontend.md#api-client)). It shows the text of the Server only for a refusal, a 4xx. A 5xx has no text for a user: its `title` is the default of ASP.NET, and a `detail` is for a developer. So for a 5xx, and for an answer that is not a problem, the SPA shows `serverFaultMessage` of `lib/problem-details.ts`. For a 504 with no body, and for a request that reaches the time limit of the SPA, it shows `timedOutMessage`. For a request with no answer, it shows `noAnswerMessage`. The `message` of the error has the same text, so a form or a page that shows the error shows no text of the Server. A component that also shows the error must not repeat the same text. When the SPA writes its own text, such as a toast, a label, or an empty state, these rules also apply. The SPA has no check for them. The `verify-fullstack-template` skill reads each message on the screen.
4 changes: 2 additions & 2 deletions docs/specs/home-rolled-bff.md
Original file line number Diff line number Diff line change
Expand Up @@ -370,7 +370,7 @@ YARP `MapForwarder("/api/{**catch-all}", "<server>/api", ...)`. The server URL c
- Remove the `Set-Cookie` values of the API response. Change: a `Set-Cookie: __Host-bff=...` from the API could replace the session cookie. The API sets no cookies today.
- A `Set-Cookie` that the BFF itself wrote in this request (a renewed BFF session) stays. YARP appends the API headers to the headers that the BFF already wrote, so a plain `ResponseHeaderRemove("Set-Cookie")` removes both. The transform must filter only the values from the proxied response.

**The forwarder.** Keep the hop-by-hop rules, the 100 s activity timeout, and the 502 or 504 error mapping. The forwarder has no retries, because a retry in a proxy can send a POST two times.
**The forwarder.** Keep the hop-by-hop rules and the 502 or 504 error mapping. Change: the activity timeout is `Bff:Proxy:ActivityTimeout` (30 s), and `Bff:Proxy:UploadActivityTimeout` (5 min) for a multipart form, in place of the 100 s default. The forwarder has no retries, because a retry in a proxy can send a POST two times.

### 3.7 Token management and the refresh lock

Expand Down Expand Up @@ -508,7 +508,7 @@ Each behavior of the current BFF, from [the inventory](https://github.com/pdevit
| 22 | Proxy `/api/{**catch-all}`, `Cookie` removed, `/api` stripped | Kept | Parity | 3.6 |
| 23 | Proxy copies a browser `Authorization` header | Changed | Removed, with `DPoP`. [#21](https://github.com/pdevito3/FullstackTemplate/issues/21) | 3.6 |
| 24 | Proxy copies `Set-Cookie` from the API | Changed | Removed. [#21](https://github.com/pdevito3/FullstackTemplate/issues/21) | 3.6 |
| 25 | Proxy `X-Forwarded-*`, hop-by-hop, 100 s timeout, 502 and 504 | Kept | Parity | 3.6 |
| 25 | Proxy `X-Forwarded-*`, hop-by-hop, 100 s timeout, 502 and 504 | Changed | The timeout is 30 s, and 5 min for an upload | 3.6 |
| 26 | Token attach with `UserOrNone` | Kept | Anonymous still forwards with no token | 3.7 |
| 27 | A failed refresh keeps the session | Changed | `invalid_grant` ends the BFF session. [#20](https://github.com/pdevito3/FullstackTemplate/issues/20) | 3.7 |
| 28 | Refreshed cookie kept in the proxied response | Kept | Parity | 3.6 |
Expand Down
35 changes: 26 additions & 9 deletions frontend/src/components/attachments/attachments-section.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,19 +9,20 @@ import { QueryError } from '@/components/query-error'
import { Button } from '@/components/ui/button'

import { AttachmentList } from './attachment-list'
import type { Attachment, AttachmentList as AttachmentListData } from './types'
import type { Attachment, AttachmentList as AttachmentListData, Upload } from './types'
import { acceptedFileTypes, uploadHint } from './upload-rules'

interface Mutation<TVariables> {
mutate: (variables: TVariables, options?: { onSuccess?: () => void }) => void
reset: () => void
isPending: boolean
variables?: TVariables
}

interface AttachmentsSectionProps {
/** The list query of the record. Its upload rules give the hint and the types that the file chooser shows. */
list: UseQueryResult<AttachmentListData>
upload: Mutation<File>
upload: Mutation<Upload>
/** Takes the ID of the attachment. */
remove: Mutation<string>
/** From `allowedActions` of the record. */
Expand All @@ -35,15 +36,24 @@ export function AttachmentsSection({ list, upload, remove, canManage, emptyText
const hintId = useId()
// A delete removes the focused row, so the focus goes to the heading of the section
const headingRef = useRef<HTMLHeadingElement>(null)
const uploadButtonRef = useRef<HTMLButtonElement>(null)
const uploadAbort = useRef<AbortController | null>(null)
const rules = list.data?.uploadRules

const handleSelect = (files: FileList | null) => {
const file = files?.[0]
if (file) {
upload.mutate(file, { onSuccess: () => Notification.success('File uploaded') })
uploadAbort.current = new AbortController()
upload.mutate({ file, signal: uploadAbort.current.signal }, { onSuccess: () => Notification.success('File uploaded') })
}
}

const handleCancelUpload = () => {
uploadAbort.current?.abort()
upload.reset()
uploadButtonRef.current?.focus()
}

const handleDelete = (attachment: Attachment) =>
remove.mutate(attachment.id, {
onSuccess: () => {
Expand All @@ -66,12 +76,19 @@ export function AttachmentsSection({ list, upload, remove, canManage, emptyText
)}
</div>
{canManage && (
<FileTrigger acceptedFileTypes={rules && acceptedFileTypes(rules)} onSelect={handleSelect}>
<Button variant="outline" isPending={upload.isPending} aria-describedby={rules && hintId}>
<HugeiconsIcon icon={Upload04Icon} aria-hidden />
{upload.isPending ? 'Uploading' : 'Upload file'}
</Button>
</FileTrigger>
<div className="flex items-center gap-2">
<FileTrigger acceptedFileTypes={rules && acceptedFileTypes(rules)} onSelect={handleSelect}>
<Button ref={uploadButtonRef} variant="outline" isPending={upload.isPending} aria-describedby={rules && hintId}>
<HugeiconsIcon icon={Upload04Icon} aria-hidden />
{upload.isPending ? 'Uploading' : 'Upload file'}
</Button>
</FileTrigger>
{upload.isPending && (
<Button variant="ghost" onPress={handleCancelUpload}>
Cancel upload
</Button>
)}
</div>
)}
</div>
<AttachmentListState
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/components/attachments/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,8 @@ export interface AttachmentList {
uploadRules: UploadRules
attachments: Attachment[]
}

export interface Upload {
file: File
signal: AbortSignal
}
2 changes: 1 addition & 1 deletion frontend/src/components/long-word.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function FilesOfOneLongFileType() {
attachments: [],
}),
})
const noWrite = { mutate: () => {}, isPending: false }
const noWrite = { mutate: () => {}, reset: () => {}, isPending: false }
return <AttachmentsSection list={list} upload={noWrite} remove={noWrite} canManage emptyText="No files." />
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ import { useMutation, useQueryClient } from '@tanstack/react-query'

import { addWorkshopAttachment } from '@/api/generated/workshops/clients/add-workshop-attachment'

import type { Upload } from '@/components/attachments/types'

import { WorkshopKeys } from './workshop.keys'

export function useAddWorkshopAttachment(workshopId: string) {
const queryClient = useQueryClient()

return useMutation({
mutationFn: (file: File) => addWorkshopAttachment({ path: { id: workshopId }, body: { file } }),
mutationFn: ({ file, signal }: Upload) => addWorkshopAttachment({ path: { id: workshopId }, body: { file }, signal }),
onSuccess: () => queryClient.invalidateQueries({ queryKey: WorkshopKeys.attachments(workshopId) }),
})
}
Loading
Loading