Renamed the Web package as Infrastructure (#25)

This PR contains the work done to rename the _Web_ package as _Infrastructure_, to provide a clear naming and purpose to this particular package within the project.

To provide further details about the work:

* Infrastructure
  * Asset fingerprinting: an FNV-1a token derived from the static files directory, appended as ?v= to asset URLs so deploys bust caches; pre-rendered pages also revalidate via weak ETags.
  * New middlewares: fixed-window RateLimitMiddleware (per-client budgets keyed by trusted X-Forwarded-For or remote address) and VaryMiddleware (Accept-Encoding on every response); SecurityHeadersMiddleware now also stamps error responses.
  * Auto-generated HEAD endpoints, cache max-age configuration, and Docker build/Compose refinements.
  * Protocols and scaffolding: Asset/AssetExtension, the Page protocol (viewport, stylesheets, scripts, versioned URLs), and LocalizedRequestContext.
  * Rate limiter's counter store swapped from an actor to a Mutex (no executor hop per request) with amortized batch eviction instead of O(n²) scans under client floods.
  * FingerprintAssets reports unreadable files to a logger instead of silently producing a token that never busts their cache.

Reviewed-on: rock-n-code/loud-amsterdam#25
Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
Co-committed-by: Javier Cicchelli <javier@rock-n-code.com>
This commit is contained in:
2026-07-23 01:04:37 +00:00
committed by javier
parent a868275347
commit cdded06ba3
58 changed files with 2844 additions and 519 deletions
+174 -5
View File
@@ -2,6 +2,7 @@ import Configuration
import Foundation
import Hummingbird
import HummingbirdTesting
import Infrastructure
import NIOCore
import Testing
@@ -12,11 +13,11 @@ import Testing
struct AppTests {
// MARK: Constants
private let textExtensions: [StaticFile.Extension] = [
// Stylesheets and scripts are referenced through fingerprinted URLs, so they are served immutable.
private let immutableExtensions: [AssetExtension] = [
.css,
.js,
.txt
.js
]
// Absolute path to the package's "Resources/Static" folder, derived from this
@@ -48,6 +49,22 @@ struct AppTests {
}
}
@Test
func `landing page to answer a head request`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/",
method: .head
) { response in
#expect(response.status == .ok)
#expect(response.headers[.contentType] == "text/html; charset=utf-8")
#expect(response.body.readableBytes == 0)
}
}
}
@Test
func `health check to be served at the health path`() async throws {
try await app(
@@ -106,7 +123,9 @@ struct AppTests {
#expect(cacheControl.contains("public") == true)
#expect(cacheControl.contains("max-age=") == true)
if textExtensions.contains(fileExtension) {
if immutableExtensions.contains(fileExtension) {
#expect(cacheControl.contains("immutable") == true)
} else if fileExtension == .txt {
#expect(cacheControl.contains("must-revalidate") == true)
}
}
@@ -114,6 +133,81 @@ struct AppTests {
}
}
@Test
func `versioned asset URL to be served`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/css/shared.css?v=0123456789abcdef",
method: .get
) { response in
#expect(response.status == .ok)
#expect(response.headers[.contentType] == "text/css")
}
}
}
@Test
func `landing page to reference fingerprinted assets`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/",
method: .get
) { response in
let body = String(buffer: response.body)
#expect(body.contains("/css/shared.css?v="))
#expect(body.contains("/js/shared.js?v="))
}
}
}
@Test
func `landing page to revalidate with an entity tag`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
let eTag = try await client.execute(
uri: "/",
method: .get
) { response in
#expect(response.headers[.cacheControl] == "public, no-cache")
return try #require(response.headers[.eTag])
}
try await client.execute(
uri: "/",
method: .get,
headers: [.ifNoneMatch: eTag]
) { response in
#expect(response.status == .notModified)
#expect(response.body.readableBytes == 0)
#expect(response.headers[.eTag] == eTag)
}
}
}
@Test
func `responses to vary on language and encoding`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/",
method: .get
) { response in
let vary = try #require(response.headers[.vary])
#expect(vary.contains("Accept-Language"))
#expect(vary.contains("Accept-Encoding"))
}
}
}
@Test
func `response to be compressed when the client supports it`() async throws {
try await app(
@@ -163,6 +257,81 @@ struct AppTests {
}
}
@Test
func `error page to reference fingerprinted assets`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get
) { response in
let body = String(buffer: response.body)
#expect(body.contains("/css/error.css?v="))
#expect(body.contains("/js/shared.js?v="))
}
}
}
@Test
func `error page to be served without revalidation headers`() async throws {
// A `304 Not Modified` only ever stands in for a success, so the error page must not
// invite revalidation with an entity tag or a cache policy.
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get
) { response in
#expect(response.status == .notFound)
#expect(response.headers[.eTag] == nil)
#expect(response.headers[.cacheControl] == nil)
}
}
}
@Test
func `error page to vary on language and encoding`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get
) { response in
let vary = try #require(response.headers[.vary])
#expect(vary.contains("Accept-Language"))
#expect(vary.contains("Accept-Encoding"))
}
}
}
@Test
func `landing page to revalidate a conditional head request`() async throws {
try await app(
staticFilesPath: staticFilesPath
).test(.router) { client in
let eTag = try await client.execute(
uri: "/",
method: .get
) { response in
try #require(response.headers[.eTag])
}
try await client.execute(
uri: "/",
method: .head,
headers: [.ifNoneMatch: eTag]
) { response in
#expect(response.status == .notModified)
#expect(response.body.readableBytes == 0)
}
}
}
@Test
func `security headers to be applied to the landing page`() async throws {
try await app(
@@ -1,3 +1,4 @@
import Infrastructure
import Testing
@testable import WebsiteLibrary
@@ -8,7 +9,6 @@ struct StaticFileTests {
// MARK: Type aliases
typealias File = StaticFile
typealias FileExtension = StaticFile.Extension
// MARK: Computed tests
@@ -18,7 +18,7 @@ struct StaticFileTests {
))
func `file extensions`(
for file: File,
expects extensions: [FileExtension]
expects extensions: [AssetExtension]
) {
#expect(file.fileExtensions == extensions)
}
@@ -34,81 +34,6 @@ struct StaticFileTests {
#expect(file.fileName == fileName)
}
@Test(arguments: zip(
Self.extensions,
Self.contentTypes
))
func `content type`(
for fileExtension: FileExtension,
expects contentType: String
) {
#expect(fileExtension.contentType == contentType)
}
@Test(arguments: zip(
Self.extensions,
Self.subdirectories
))
func `subdirectory`(
for fileExtension: FileExtension,
expects subdirectory: String?
) {
#expect(fileExtension.subdirectory == subdirectory)
}
// MARK: Method tests
@Test(arguments: zip(
File.allCases,
Self.relativePaths
))
func `relative path for`(
for file: File,
expects relativePaths: [String]
) {
for (fileExtension, relativePath) in zip(file.fileExtensions, relativePaths) {
#expect(file.relativePath(for: fileExtension) == relativePath)
}
}
@Test(arguments: zip(
File.allCases,
Self.relativePaths
))
func `url path for`(
for file: File,
expects relativePaths: [String]
) {
for (fileExtension, relativePath) in zip(file.fileExtensions, relativePaths) {
#expect(file.urlPath(for: fileExtension) == "/\(relativePath)")
}
}
@Test(arguments: [
"",
".",
"Resources/Static"
])
func `path relative to`(
_ basePath: String
) {
for file in File.allCases {
for fileExtension in file.fileExtensions {
let pathRelativeToBasePath = file.path(
relativeTo: basePath,
for: fileExtension
)
let relativePath = file.relativePath(for: fileExtension)
if basePath.isEmpty {
#expect(pathRelativeToBasePath == relativePath)
} else {
#expect(pathRelativeToBasePath == "\(basePath)/\(relativePath)")
}
}
}
}
// MARK: CaseIterable tests
@Test
@@ -124,37 +49,7 @@ private extension StaticFileTests {
// MARK: Constants
static let extensions: [FileExtension] = [
.css,
.js,
.png,
.ico,
.svg,
.txt,
.webmanifest,
.xml
]
static let contentTypes: [String] = [
"text/css",
"text/javascript",
"image/png",
"image/vnd.microsoft.icon",
"image/svg+xml",
"text/plain",
"application/manifest+json",
"application/xml"
]
static let subdirectories: [String?] = [
"css",
"js",
nil,
nil,
nil,
nil,
nil,
nil
]
static let fileExtensions: [[FileExtension]] = [
static let fileExtensions: [[AssetExtension]] = [
[.png],
[.css, .js],
[.ico],
@@ -180,18 +75,5 @@ private extension StaticFileTests {
"site",
"sitemap"
]
static let relativePaths: [[String]] = [
["apple-touch-icon.png"],
["css/error.css", "js/error.js"],
["favicon.ico"],
["icon.svg"],
["icon-192.png"],
["icon-512.png"],
["css/index.css", "js/index.js"],
["robots.txt"],
["css/shared.css", "js/shared.js"],
["site.webmanifest"],
["sitemap.xml"]
]
}
@@ -29,4 +29,18 @@ struct IndexPageTests {
#expect(html.contains("/js/index.js"))
}
@Test
func `renders versioned asset URLs when given a version`() {
let html = IndexPage(
locale: .init(identifier: "en"),
assetVersion: "0123456789abcdef"
).render()
#expect(html.contains("/css/shared.css?v=0123456789abcdef"))
#expect(html.contains("/css/index.css?v=0123456789abcdef"))
#expect(html.contains("/js/shared.js?v=0123456789abcdef"))
#expect(html.contains("/js/index.js?v=0123456789abcdef"))
#expect(html.contains("/favicon.ico?v=0123456789abcdef"))
}
}
@@ -1,5 +1,6 @@
import Hummingbird
import HummingbirdTesting
import Infrastructure
import NIOCore
import Testing
@@ -42,4 +43,117 @@ struct RootControllerTests {
}
}
@Test
func `serves the landing page with revalidation headers`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/",
method: .get
) { response in
let eTag = try #require(response.headers[.eTag])
#expect(eTag.hasPrefix(#"W/""#))
#expect(response.headers[.cacheControl] == "public, no-cache")
}
}
}
@Test
func `revalidates a matching conditional request with a 304`() async throws {
try await app.test(.router) { client in
let eTag = try await client.execute(
uri: "/",
method: .get
) { response in
try #require(response.headers[.eTag])
}
try await client.execute(
uri: "/",
method: .get,
headers: [.ifNoneMatch: eTag]
) { response in
#expect(response.status == .notModified)
#expect(response.headers[.eTag] == eTag)
#expect(response.body.readableBytes == 0)
}
}
}
@Test
func `serves the full page to a non-matching conditional request`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/",
method: .get,
headers: [.ifNoneMatch: #"W/"0123456789abcdef""#]
) { response in
let body = String(buffer: response.body)
#expect(response.status == .ok)
#expect(body.contains("Hello world!"))
}
}
}
@Test
func `renders versioned asset URLs when given a version`() async throws {
try await app(
assetVersion: "0123456789abcdef"
).test(.router) { client in
try await client.execute(
uri: "/",
method: .get
) { response in
let body = String(buffer: response.body)
#expect(body.contains("/css/index.css?v=0123456789abcdef"))
#expect(body.contains("/js/index.js?v=0123456789abcdef"))
}
}
}
@Test
func `renders unversioned asset URLs by default`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/",
method: .get
) { response in
let body = String(buffer: response.body)
#expect(body.contains(#"href="/css/index.css""#))
#expect(!body.contains("?v="))
}
}
}
}
// MARK: - Helpers
private extension RootControllerTests {
// MARK: Methods
/// Builds an application whose root controller appends the given version token to the landing
/// page's asset URLs.
/// - Parameter assetVersion: the version token appended to the page's asset URLs.
/// - Returns: the configured application.
func app(
assetVersion: String?
) -> some ApplicationProtocol {
let router = Router(context: WebsiteRequestContext.self)
router.addMiddleware {
LocalizationMiddleware()
}
router.addRoutes(RootController<WebsiteRequestContext>(
assetVersion: assetVersion
).routes)
return Application(router: router)
}
}
@@ -4,6 +4,8 @@ import HummingbirdTesting
import NIOCore
import Testing
import Infrastructure
@testable import WebsiteLibrary
@Suite("LocalizationMiddleware middleware", .tags(.middleware))
@@ -3,6 +3,8 @@ import HummingbirdTesting
import NIOCore
import Testing
import Infrastructure
@testable import WebsiteLibrary
@Suite("NotFoundMiddleware middleware", .tags(.middleware))
@@ -70,11 +72,102 @@ struct NotFoundMiddlewareTests {
method: .get
) { response in
let body = String(buffer: response.body)
#expect(response.status == .badRequest)
#expect(!body.contains("Page Not Found"))
}
}
}
@Test
func `renders versioned asset URLs when given a version`() async throws {
try await app(
assetVersion: "0123456789abcdef"
).test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get
) { response in
let body = String(buffer: response.body)
#expect(body.contains("/css/error.css?v=0123456789abcdef"))
#expect(body.contains("/js/shared.js?v=0123456789abcdef"))
}
}
}
@Test
func `renders unversioned asset URLs by default`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get
) { response in
let body = String(buffer: response.body)
#expect(body.contains(#"href="/css/error.css""#))
#expect(!body.contains("?v="))
}
}
}
@Test
func `serves the error page without revalidation headers`() async throws {
// A `304 Not Modified` only ever stands in for a success, so the error page must not
// invite revalidation with an entity tag or a cache policy.
try await app.test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get
) { response in
#expect(response.status == .notFound)
#expect(response.headers[.eTag] == nil)
#expect(response.headers[.cacheControl] == nil)
}
}
}
@Test
func `serves the full error page to a conditional request`() async throws {
try await app.test(.router) { client in
try await client.execute(
uri: "/this-path-does-not-exist",
method: .get,
headers: [.ifNoneMatch: "*"]
) { response in
let body = String(buffer: response.body)
#expect(response.status == .notFound)
#expect(body.contains("Page Not Found"))
}
}
}
}
// MARK: - Helpers
private extension NotFoundMiddlewareTests {
// MARK: Methods
/// Builds an application whose not-found middleware appends the given version token to the
/// error page's asset URLs.
/// - Parameter assetVersion: the version token appended to the page's asset URLs.
/// - Returns: the configured application.
func app(
assetVersion: String?
) -> some ApplicationProtocol {
let router = Router(context: WebsiteRequestContext.self)
router.addMiddleware {
LocalizationMiddleware()
NotFoundMiddleware(
assetVersion: assetVersion
)
}
return Application(router: router)
}
}
@@ -1,134 +0,0 @@
import Hummingbird
import HummingbirdTesting
import Testing
@testable import WebsiteLibrary
@Suite("SecurityHeadersMiddleware middleware", .tags(.middleware))
struct SecurityHeadersMiddlewareTests {
// MARK: Functional tests
@Test
func `applies the default security headers to a response`() async throws {
try await app().test(.router) { client in
try await client.execute(
uri: "/hello",
method: .get
) { response in
#expect(response.status == .ok)
#expect(response.headers[.contentSecurityPolicy] == String.Security.contentSecurityPolicy)
#expect(response.headers[.xContentTypeOptions] == String.Security.contentTypeOptions)
#expect(response.headers[.frameOptions] == String.Security.frameOptions)
#expect(response.headers[.referrerPolicy] == String.Security.referrerPolicy)
#expect(response.headers[.permissionsPolicy] == String.Security.permissionsPolicy)
}
}
}
@Test
func `omits strict-transport-security by default`() async throws {
try await app().test(.router) { client in
try await client.execute(
uri: "/hello",
method: .get
) { response in
#expect(response.headers[.strictTransportSecurity] == nil)
}
}
}
@Test
func `applies strict-transport-security when configured`() async throws {
let value = "max-age=31536000; includeSubDomains"
try await app(
configuration: .init(strictTransportSecurity: value)
).test(.router) { client in
try await client.execute(
uri: "/hello",
method: .get
) { response in
#expect(response.headers[.strictTransportSecurity] == value)
}
}
}
@Test
func `applies a custom header value`() async throws {
let value = "default-src 'none'"
try await app(
configuration: .init(contentSecurityPolicy: value)
).test(.router) { client in
try await client.execute(
uri: "/hello",
method: .get
) { response in
#expect(response.headers[.contentSecurityPolicy] == value)
}
}
}
@Test
func `omits a header whose configured value is nil`() async throws {
try await app(
configuration: .init(contentTypeOptions: nil)
).test(.router) { client in
try await client.execute(
uri: "/hello",
method: .get
) { response in
#expect(response.headers[.xContentTypeOptions] == nil)
}
}
}
@Test
func `replaces an existing header value set downstream`() async throws {
try await app().test(.router) { client in
try await client.execute(
uri: "/weak",
method: .get
) { response in
#expect(response.headers[.xContentTypeOptions] == String.Security.contentTypeOptions)
}
}
}
}
// MARK: - Helpers
private extension SecurityHeadersMiddlewareTests {
// MARK: Methods
/// Builds an application whose router applies the security-headers middleware ahead of two
/// routes: `/hello` returns a plain body, and `/weak` returns a response that already carries a
/// deliberately weak `X-Content-Type-Options` value for the middleware to override.
func app(
configuration: SecurityHeadersMiddleware<BasicRequestContext>.Configuration = .init()
) -> some ApplicationProtocol {
let router = Router()
router.addMiddleware {
SecurityHeadersMiddleware(configuration: configuration)
}
router.get("hello") { _, _ in
"Hello!"
}
router.get("weak") { _, _ -> Response in
var response = Response(status: .ok)
response.headers[.xContentTypeOptions] = "weak"
return response
}
return Application(router: router)
}
}