Read-only mirrors. Development, issues and pull requests are on GitHub.

summaryrefslogtreecommitdiffhomepage
path: root/apps/api/Security/ForwardedHeadersPolicy.cs
blob: 046ad56fff08408a0a2ba24c8940613960565c58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com>
// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1

using System.Net;
using Microsoft.AspNetCore.HttpOverrides;

namespace Progmasoft.Progmaweb.Api.Security;

internal static class ForwardedHeadersPolicy
{
    internal const int MaximumForwardedHops = 1;
    internal static readonly IPAddress[] TrustedProxies = [IPAddress.Loopback, IPAddress.IPv6Loopback];

    public static void Configure(ForwardedHeadersOptions options)
    {
        options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedHost |
            ForwardedHeaders.XForwardedProto;
        options.ForwardLimit = MaximumForwardedHops;

        // The API is bound to loopback and only receives forwarded headers from the local Nginx/Next.js proxy.
        // Trusting every peer would let a direct caller forge the IP used by the authentication rate limiter.
        options.KnownIPNetworks.Clear();
        options.KnownProxies.Clear();
        foreach (IPAddress trustedProxy in TrustedProxies)
        {
            options.KnownProxies.Add(trustedProxy);
        }
    }
}