Initial commit: labeled multi-level file storage

Tenant separation by process, schema and Postgres grants; label separation
by row-level security inside each tenant. Node keys wrap to their label key
rather than their parent folder's, so the lattice survives a stolen backup.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Paul Hitt
2026-08-21 12:24:24 -04:00
co-authored by Claude Opus 5
commit b98220b226
35 changed files with 3338 additions and 0 deletions
+6
View File
@@ -0,0 +1,6 @@
.build/
.git/
.env
*.xcodeproj
Tests/
docs/
+24
View File
@@ -0,0 +1,24 @@
# Copy to .env and fill in. Never commit .env.
#
# Generate each secret with:
# openssl rand -base64 36
# Postgres superuser/owner password. Used only by migrations.
POSTGRES_PASSWORD=
# Password for the per-tenant role the server actually connects as.
ENCLAVE_TENANT_PASSWORD=
# Verifies the clearance tokens minted by your control plane. Minimum 32 chars.
# Rotating this invalidates every outstanding session.
ENCLAVE_JWT_SECRET=
# Tenant slug: lowercase letters, digits, underscore; 2-39 chars.
# Becomes schema "t_<slug>" and role "tenant_<slug>".
ENCLAVE_TENANT=default
# Bind address for the published port. Leave as 127.0.0.1 and put a TLS
# terminating reverse proxy in front; 0.0.0.0 exposes the app directly.
ENCLAVE_BIND=127.0.0.1
LOG_LEVEL=info
+5
View File
@@ -0,0 +1,5 @@
.build/
.swiftpm/
.env
*.xcodeproj
DerivedData/
+194
View File
@@ -0,0 +1,194 @@
# Enclave
A Drive-style file service with Solaris-Zones-shaped tenant separation and
Oracle-Label-Security-shaped classification inside each tenant.
Working name; rename freely.
## Two axes, two mechanisms
| Axis | Analogue | Boundary | Enforced by |
|---|---|---|---|
| **Tenant** | Solaris zone / Oracle PDB | process + schema + DB role | OS process separation, Postgres **grants** |
| **Label** | Trusted Extensions / Oracle OLS | rows within a tenant | Postgres **RLS** |
Keeping these separate is the whole design. A process per (tenant × label) would
be combinatorial -- compartment sets are power-set sized -- so tenants get
processes and labels get row policies. The two mechanisms are independent: a bug
in the label lattice cannot leak across tenants, because grants stop it.
## Layout
```
Sources/EnclaveLattice/ Label, Classification, Compartments, Clearance. No deps.
Sources/EnclaveAccess/ Policy decisions, labeled-tree rules. Depends on lattice only.
sql/001_shared.sql enclave.* helpers + enclave_control.* registry.
sql/002_tenant_template.sql Per-tenant schema, RLS policies, tree trigger.
```
The two libraries are deliberately free of Vapor, Fluent, and Foundation-heavy
types: the security core should be testable without a server, and reusable from
a CLI or a sync daemon.
## The tenant axis is invisible to application code
Each tenant gets a schema, a role, and a worker process. The role carries a
fixed search path:
```sql
ALTER ROLE tenant_acme SET search_path = t_acme, enclave;
```
Fluent models then declare plain table names and resolve into the right schema
automatically. No tenant ID threaded through queries, no `.filter(\.$tenant)`
that someone can forget. A worker holding `tenant_acme` credentials physically
cannot address another tenant's tables -- there is no grant to do so.
Cost to be aware of: migrations run once per schema. The control plane loops
them; Fluent's `_fluent_migrations` lands inside each tenant schema, which gives
per-tenant version tracking for free.
## The label axis, and the one thing that must be right
Every request runs inside a transaction that first pins the session label:
```swift
extension Request {
/// The ONLY sanctioned path to the database. `req.db` is not vended.
func labeled<T>(_ body: (any Database) async throws -> T) async throws -> T {
let label = try requireSessionLabel() // set by the auth middleware
return try await db.transaction { db in
guard let sql = db as? any SQLDatabase else { throw Abort(.internalServerError) }
// SET LOCAL takes no bind parameters; set_config(..., is_local: true)
// is the parameterised equivalent and is injection-safe.
try await sql.raw("""
SELECT set_config('enclave.classification', \(bind: String(label.classification.rawValue)), true),
set_config('enclave.compartments', \(bind: String(label.compartments.postgresBitPattern)), true)
""").run()
return try await body(db)
}
}
}
```
Three properties worth understanding:
1. **`SET LOCAL` is transaction-scoped**, so a pooled connection cannot leak one
user's label into another's request. This is why the wrapper is a transaction
and not a connection hook.
2. **Forgetting it fails closed.** Unset GUCs read as NULL, every dominance test
evaluates to NULL, and RLS treats NULL as false -- the query returns nothing.
Safe, but the symptom is an empty result set rather than an error, so the
middleware asserts the label is present instead of relying on this.
3. **Do not expose `req.db`.** The single greatest risk in this design is a
handler that reaches past the wrapper. Make the raw database internal, vend
only `req.labeled`, and add a CI grep for direct `req.db` use.
## What Fluent gives you for free
RLS filters below the ORM, so `Node.find(id, on: db)` returns `nil` for a row
the session does not dominate -- identical to a row that does not exist. Your
handler's ordinary `guard let ... else { throw Abort(.notFound) }` is already
the correct inference-controlled response. The 404-not-403 rule that usually
takes discipline to maintain falls out of the stack.
`Decision.httpStatus` in `EnclaveAccess` exists for the paths where you compute
a decision in Swift rather than letting the database do it -- keep those few.
## Labeled-tree rules
Two invariants, enforced in `Tree.swift` and again as database constraints:
- **A child's label dominates its parent's.** A SECRET file inside a
CONFIDENTIAL folder is fine and normal; the inverse strands the child, since
nobody could traverse to it. The trigger's parent lookup runs under the
caller's RLS, so an invisible parent is rejected exactly like a missing one.
- **Names are polyinstantiated.** Uniqueness is
`(parent, name, classification, compartments)`. A plain `UNIQUE(parent, name)`
turns a constraint violation into an existence oracle: create "Payroll", get a
duplicate-key error, and you have learned that a file you cannot see exists.
Resolution prefers an exact session-label match, then the unique most-sensitive
visible instance, and reports genuine ambiguity rather than guessing -- two
incomparable siblings sharing a name have no defensible winner.
## Covert channels closed on purpose
- **No cross-label deduplication.** Identical bytes at two labels are two blobs.
Collapsing them lets a low-cleared user probe for high-labeled content by
watching storage accounting or upload timing.
- **Per-label quota.** A tenant-wide free-space figure signals high-label
activity to low-cleared users.
- **Labeled audit rows.** The log carries the label of what it describes, so the
audit trail cannot become the leak.
Each costs real efficiency. They are deliberate.
## Regrade
Moving a node down the lattice is the only privileged operation, and there is no
code path that mutates a node's label directly -- the RLS UPDATE policy's
`WITH CHECK` forbids relabelling by ordinary write. Downgrades go through
`regrade_requests`: justification, two distinct reviewers neither of whom is the
requester, and an immutable record. Upgrades are free.
This workflow, not the lattice, is where the product value sits.
## Encryption: zero-knowledge
Server holds ciphertext only. Three levels:
```
identity key per user, from passphrase; never leaves the client
│ wraps
label key one per label in use; wrapped to every cleared principal
│ wraps
node key one per file/folder
│ wraps
content key one per revision
```
**Node keys wrap to the node's LABEL key, never to the parent folder's key.**
The tree invariant permits a RESTRICTED file inside a CONFIDENTIAL folder, so
parent-derived keys -- the conventional Drive design -- would hand every holder
of the folder key content above their clearance. RLS would still refuse to serve
it; a backup, snapshot, or compromised server would not. `KeyHierarchy.validate`
and the `node_keys` trigger both enforce this.
Filenames are ciphertext; uniqueness and lookup run on
`HMAC(folder_key, normalise(name))`, keyed per folder so the server cannot
invert names or correlate them across folders.
### Consequences, stated plainly
- **No deduplication at all.** Convergent encryption would give the server a
confirmation-of-file oracle, and across labels that is also a covert channel.
- **No server-side search.** A client-side encrypted index is the honest answer,
and it caps practical library size.
- **Regrade cannot inspect content.** The guard workflow is procedural: cleared
reviewers decrypt in their own client. No server-side content scanning.
- **Downgrades need a cleared client.** Re-encrypting under the lower label key
is work the server cannot do, so `approved` waits for a client to rewrap and
only that client can move the request to `applied`.
- **Revocation is imperfect.** Removing a compartment rotates the label key, but
a user who held the old key retains it. Prior content stays readable to them
until re-encrypted. Design the rotation; do not paper over the gap.
- **Password reset destroys data** unless recovery phrases exist from day one.
### What Leaf still renders
Auth, the app shell, and the whole control plane -- tenant config, clearance
administration, audit metadata, regrade queues. None of that is E2E, so Leaf
does real work there. The file browser itself is a JS surface that decrypts
client-side.
### Claim discipline
The web client fetches its JavaScript from your server on every load. A
compromised or coerced server can serve key-capturing code, so **"we cannot read
your files" is not truthfully claimable for the web client** -- only for a
native client with a pinned, signed binary. Say "encrypted in your browser
before upload"; keep the absolute claim for the native apps, once they exist.
+39
View File
@@ -0,0 +1,39 @@
# ---- build ------------------------------------------------------------------
FROM swift:6.0-jammy AS build
WORKDIR /build
# Resolve dependencies first so edits to source do not invalidate the layer.
COPY Package.swift Package.resolved ./
RUN swift package resolve --skip-update
COPY Sources ./Sources
COPY Tests ./Tests
COPY Resources ./Resources
# Static stdlib keeps the runtime image free of a Swift installation.
RUN swift build -c release --product EnclaveServer --static-swift-stdlib
WORKDIR /staging
RUN BIN="$(swift build --package-path /build -c release --show-bin-path)" \
&& cp "$BIN/EnclaveServer" ./ \
&& find -L "$BIN" -regex '.*\.resources$' -exec cp -Ra {} ./ \; \
&& cp -r /build/Resources ./Resources
# ---- runtime ----------------------------------------------------------------
FROM ubuntu:jammy
RUN apt-get update \
&& apt-get install -y --no-install-recommends ca-certificates tzdata libcurl4 libxml2 \
&& rm -rf /var/lib/apt/lists/*
# Never run as root. The server needs no write access to its own image.
RUN useradd --user-group --create-home --system --skel /dev/null --home-dir /app enclave
WORKDIR /app
COPY --from=build --chown=enclave:enclave /staging /app
USER enclave:enclave
EXPOSE 8080
ENTRYPOINT ["./EnclaveServer"]
CMD ["serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"]
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Extant 2000 LLC
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+357
View File
@@ -0,0 +1,357 @@
{
"originHash" : "70c0fbc656e2d73b839111d6aacac513c16b5d2b3fdd63cfc747f5bcd38efb3f",
"pins" : [
{
"identity" : "async-http-client",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/async-http-client.git",
"state" : {
"revision" : "9544287b9416c0bc71e58b9f3aead8dd14b16103",
"version" : "1.36.0"
}
},
{
"identity" : "async-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/async-kit.git",
"state" : {
"revision" : "6bbb83cbf9d886623a967a965c8fb1b73e6566f9",
"version" : "1.22.0"
}
},
{
"identity" : "console-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/console-kit.git",
"state" : {
"revision" : "15121e1ec44a0a2064e43545d1390f02cc19b07d",
"version" : "4.16.1"
}
},
{
"identity" : "fluent",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/fluent.git",
"state" : {
"revision" : "2fe9e36daf4bdb5edcf193e0d0806ba2074d2864",
"version" : "4.13.0"
}
},
{
"identity" : "fluent-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/fluent-kit.git",
"state" : {
"revision" : "ca609b2132bde05f9a2d7561e2864587c24fa7b9",
"version" : "1.57.0"
}
},
{
"identity" : "fluent-postgres-driver",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/fluent-postgres-driver.git",
"state" : {
"revision" : "59bff45a41d1ece1950bb8a6e0006d88c1fb6e69",
"version" : "2.12.0"
}
},
{
"identity" : "jwt",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/jwt.git",
"state" : {
"revision" : "af1c59762d70d1065ddbc0d7902ea9b3dacd1a26",
"version" : "5.1.2"
}
},
{
"identity" : "jwt-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/jwt-kit.git",
"state" : {
"revision" : "7abc497b0f907191933c87166e9b6a41b9d028d6",
"version" : "5.6.0"
}
},
{
"identity" : "leaf",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/leaf.git",
"state" : {
"revision" : "21852a898dc8681ec072f79968f1c21fb87da8cb",
"version" : "4.5.2"
}
},
{
"identity" : "leaf-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/leaf-kit.git",
"state" : {
"revision" : "64cc0a5c8dcf4fbd03be73b944f6850c0b82e439",
"version" : "1.14.3"
}
},
{
"identity" : "multipart-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/multipart-kit.git",
"state" : {
"revision" : "3498e60218e6003894ff95192d756e238c01f44e",
"version" : "4.7.1"
}
},
{
"identity" : "postgres-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/postgres-kit.git",
"state" : {
"revision" : "218aaf6810db9e61398f887aaaf26424142bdb53",
"version" : "2.16.1"
}
},
{
"identity" : "postgres-nio",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/postgres-nio.git",
"state" : {
"revision" : "39ce38a93408937bcd27f521f3cdf88266136b80",
"version" : "1.33.1"
}
},
{
"identity" : "routing-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/routing-kit.git",
"state" : {
"revision" : "1a10ccea61e4248effd23b6e814999ce7bdf0ee0",
"version" : "4.9.3"
}
},
{
"identity" : "sql-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/sql-kit.git",
"state" : {
"revision" : "3779cedb44b1f374f2cca261c6d28f206024a582",
"version" : "3.36.0"
}
},
{
"identity" : "swift-algorithms",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-algorithms.git",
"state" : {
"revision" : "87e50f483c54e6efd60e885f7f5aa946cee68023",
"version" : "1.2.1"
}
},
{
"identity" : "swift-asn1",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-asn1.git",
"state" : {
"revision" : "a9a5efd40eaf558a2bcd48d64b1d1646be686008",
"version" : "1.7.1"
}
},
{
"identity" : "swift-async-algorithms",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-async-algorithms.git",
"state" : {
"revision" : "3da39bbc4e687d4192af7c9cf4eab805745a0b9c",
"version" : "1.1.5"
}
},
{
"identity" : "swift-atomics",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-atomics.git",
"state" : {
"revision" : "0442cb5a3f98ab802acb777929fdb446bda11a34",
"version" : "1.3.1"
}
},
{
"identity" : "swift-certificates",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-certificates.git",
"state" : {
"revision" : "449dbbecd0f31e82b510ada227ca152caa8b5e98",
"version" : "1.19.4"
}
},
{
"identity" : "swift-collections",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-collections.git",
"state" : {
"revision" : "a0cb0954ecb21e4e31b0070e6ed5674e8556685a",
"version" : "1.6.0"
}
},
{
"identity" : "swift-configuration",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-configuration.git",
"state" : {
"revision" : "be76c4ad929eb6c4bcaf3351799f2adf9e6848a9",
"version" : "1.2.0"
}
},
{
"identity" : "swift-crypto",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-crypto.git",
"state" : {
"revision" : "47d3869a7291f085c1fb9fb1e6d3b97a793f45c6",
"version" : "4.5.1"
}
},
{
"identity" : "swift-distributed-tracing",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-distributed-tracing.git",
"state" : {
"revision" : "dc4030184203ffafbb2ec614352487235d747fe0",
"version" : "1.4.1"
}
},
{
"identity" : "swift-http-structured-headers",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-http-structured-headers.git",
"state" : {
"revision" : "933538faa42c432d385f02e07df0ace7c5ecfc47",
"version" : "1.7.0"
}
},
{
"identity" : "swift-http-types",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-http-types.git",
"state" : {
"revision" : "db774a277f60063a32d854f2980299caf06da041",
"version" : "1.6.0"
}
},
{
"identity" : "swift-log",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-log.git",
"state" : {
"revision" : "3ffafb9722d5d918c614feb496c8789a3b59d222",
"version" : "1.15.0"
}
},
{
"identity" : "swift-metrics",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-metrics.git",
"state" : {
"revision" : "087e8074afa97040c3b870c8664fe5482fb87cc4",
"version" : "2.11.0"
}
},
{
"identity" : "swift-nio",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio.git",
"state" : {
"revision" : "0b18836bd8b0162e7e17a995a3fbee20ed8f3b2b",
"version" : "2.101.3"
}
},
{
"identity" : "swift-nio-extras",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-extras.git",
"state" : {
"revision" : "88a51340f59cf181ebde888bd1b749296b3ec029",
"version" : "1.34.3"
}
},
{
"identity" : "swift-nio-http2",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-http2.git",
"state" : {
"revision" : "45bdf670248be5f16ec0340e125dca285536f0fb",
"version" : "1.45.0"
}
},
{
"identity" : "swift-nio-ssl",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-ssl.git",
"state" : {
"revision" : "d930168b86f46ca51a4bc09c5ca45c1833db8067",
"version" : "2.37.2"
}
},
{
"identity" : "swift-nio-transport-services",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-nio-transport-services.git",
"state" : {
"revision" : "67787bb645a5e67d2edcdfbe48a216cc549222d5",
"version" : "1.28.0"
}
},
{
"identity" : "swift-numerics",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-numerics.git",
"state" : {
"revision" : "0c0290ff6b24942dadb83a929ffaaa1481df04a2",
"version" : "1.1.1"
}
},
{
"identity" : "swift-service-context",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-service-context.git",
"state" : {
"revision" : "d0997351b0c7779017f88e7a93bc30a1878d7f29",
"version" : "1.3.0"
}
},
{
"identity" : "swift-service-lifecycle",
"kind" : "remoteSourceControl",
"location" : "https://github.com/swift-server/swift-service-lifecycle.git",
"state" : {
"revision" : "7f9326b0326ff86e3646295ea6e891f68c471c5e",
"version" : "2.12.0"
}
},
{
"identity" : "swift-system",
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-system.git",
"state" : {
"revision" : "869129b7bf4ecc57b97d0193ad29690ca2134750",
"version" : "1.8.1"
}
},
{
"identity" : "vapor",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/vapor.git",
"state" : {
"revision" : "748ae8432a33e0965bbf0351fedd4e915e7f460c",
"version" : "4.122.0"
}
},
{
"identity" : "websocket-kit",
"kind" : "remoteSourceControl",
"location" : "https://github.com/vapor/websocket-kit.git",
"state" : {
"revision" : "90bbbdab3ede12c803cfbe91646f291c092517a3",
"version" : "2.16.2"
}
}
],
"version" : 3
}
+46
View File
@@ -0,0 +1,46 @@
// swift-tools-version:6.0
import PackageDescription
let package = Package(
name: "Enclave",
platforms: [.macOS(.v14)],
products: [
.library(name: "EnclaveLattice", targets: ["EnclaveLattice"]),
.library(name: "EnclaveAccess", targets: ["EnclaveAccess"]),
.library(name: "EnclaveCrypto", targets: ["EnclaveCrypto"]),
.executable(name: "EnclaveServer", targets: ["EnclaveServer"]),
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.106.0"),
.package(url: "https://github.com/vapor/fluent.git", from: "4.9.0"),
.package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.9.0"),
.package(url: "https://github.com/vapor/leaf.git", from: "4.3.0"),
.package(url: "https://github.com/vapor/jwt.git", from: "5.0.0"),
],
targets: [
// The security core stays dependency-free and in strict Swift 6 mode.
.target(name: "EnclaveLattice"),
.target(name: "EnclaveCrypto", dependencies: ["EnclaveLattice"]),
.target(name: "EnclaveAccess", dependencies: ["EnclaveLattice", "EnclaveCrypto"]),
.executableTarget(
name: "EnclaveServer",
dependencies: [
"EnclaveLattice", "EnclaveAccess", "EnclaveCrypto",
.product(name: "Vapor", package: "vapor"),
.product(name: "Fluent", package: "fluent"),
.product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"),
.product(name: "Leaf", package: "leaf"),
.product(name: "JWT", package: "jwt"),
],
resources: [.copy("SQL")],
// Fluent's property wrappers on model classes do not yet satisfy
// Swift 6 strict concurrency. The security core above is compiled in
// v6 mode; only this target is held back, and only until Fluent
// catches up.
swiftSettings: [.swiftLanguageMode(.v5)]
),
.testTarget(name: "EnclaveLatticeTests", dependencies: ["EnclaveAccess"]),
]
)
+109
View File
@@ -0,0 +1,109 @@
# enclave
Self-hostable encrypted file storage with **multi-level security** — a Drive
where every file carries a classification label, the lattice is enforced by the
database on metadata and by the key hierarchy on content, and the server can
read neither filenames nor file contents.
The model is borrowed from Solaris Zones and Trusted Extensions for runtime
separation, and from Oracle Label Security for row-level classification. The
encryption posture is the one behind
[FlameNet Messenger](https://flamenetmessenger.com): keys are derived on the
client and the server holds ciphertext.
⚠️ **This is early. It is not finished software** — see [Status](#status) for
what exists and what does not. Do not put real data in it yet.
## What it is
- **Two independent boundaries.** Tenants are separated by OS process, Postgres
schema, and role grants. Labels are separated inside a tenant by row-level
security. A bug in the label logic cannot cross a tenant, because grants stop
it before the policy is consulted.
- **A real lattice, not a level number.** A label is a hierarchical
classification crossed with a set of non-hierarchical compartments. Dominance
requires both. `RESTRICTED//LEGAL` does not dominate `CONFIDENTIAL//FINANCE`,
and treating classification as a total order is the mistake this design exists
to prevent.
- **Keys follow the label, never the tree.** A node key is wrapped to its own
label key. The conventional Drive design — folder key wraps child keys — would
hand every holder of a folder key any higher-labeled file inside it, leaving
the lattice enforced only by the database. A stolen backup would read straight
through it.
- **Inference control by construction.** Failing to dominate an object is
reported as absence, never as refusal. Filenames are polyinstantiated, so a
duplicate-name error can never confirm the existence of a file you cannot see.
- **Zero-knowledge content.** Filenames and file contents are encrypted client
side. The server enforces labels on the metadata it can see: tree shape,
sizes, timestamps.
## What the server can still see
Being precise about this matters more than the headline.
| | Server sees |
|---|---|
| File contents | no |
| Filenames | no — only `HMAC(folder_key, name)` |
| Labels on every node | **yes** — this is what RLS enforces |
| Tree shape, sizes, timestamps | **yes** |
| Who holds which label key | **yes** |
## Status
Working and tested:
- `EnclaveLattice` — labels, dominance, lub/glb, clearances. 23 tests.
- `EnclaveAccess` — access decisions, labeled-tree rules, polyinstantiated
name resolution.
- `EnclaveCrypto` — key hierarchy *shape* and its invariants. Implements no
primitives by design.
- `EnclaveServer` — Vapor app: token auth, session-label middleware, the
`req.labeled` transaction wrapper, node and key routes.
- SQL schema with RLS policies, tree and key-alignment triggers, grants.
- Docker and compose for self-hosting.
Not built yet:
- **Client-side crypto.** The browser module is a placeholder. Nothing is
actually encrypted today.
- **Blob storage.** The `blobs` table exists; no upload path or object-store
backend is wired.
- **Control plane.** Token minting, tenant provisioning, and clearance
administration are external and unwritten.
- **Regrade endpoints.** The table and its two-person constraints exist; the
routes do not.
- **Sync clients.** None.
- ⚠️ **The SQL has never been executed against a live Postgres.** It is written
carefully and reviewed, but unrun.
## Quick start
```bash
cp .env.example .env # then fill in the three secrets
docker compose up --build
```
Read [SELF-HOSTING.md](SELF-HOSTING.md) first. There is one misconfiguration —
connecting the app as a Postgres superuser — that silently disables every label
check while appearing to work perfectly. The server refuses to start if it
detects this, but you should understand why.
## Documentation
- [ARCHITECTURE.md](ARCHITECTURE.md) — the design, and why each covert channel
is closed the way it is
- [SELF-HOSTING.md](SELF-HOSTING.md) — deployment, roles, backups
- [SECURITY.md](SECURITY.md) — threat model, limitations, reporting
## A claim this project does not make
The web client fetches its JavaScript from the same host that stores your data.
A compromised or coerced server can serve code that captures keys at load time.
So **"we cannot read your files" is not a claim the web client can honestly
make** — only a signed native client can, and none exists yet. The accurate
statement is that files are encrypted in your browser before upload.
## License
MIT — see [LICENSE](LICENSE).
+68
View File
@@ -0,0 +1,68 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Enclave</title>
<style>
:root { color-scheme: light dark; --fg: #16181d; --bg: #fbfbfa; --muted: #6b7280;
--line: #e3e3e0; --accent: #2f4f6f; }
@media (prefers-color-scheme: dark) {
:root { --fg: #e6e6e3; --bg: #16181d; --muted: #9aa0aa; --line: #2a2d35; --accent: #8fb3d9; }
}
body { margin: 0; font: 15px/1.55 ui-sans-serif, system-ui, sans-serif;
color: var(--fg); background: var(--bg); }
header { display: flex; align-items: center; gap: 1rem; flex-wrap: wrap;
padding: 1rem 1.25rem; border-bottom: 1px solid var(--line); }
h1 { font-size: 1rem; font-weight: 600; margin: 0; letter-spacing: .01em; }
main { padding: 1.25rem; }
.label-picker { margin-left: auto; display: flex; align-items: center; gap: .5rem;
font-size: .85rem; color: var(--muted); }
select { font: inherit; padding: .25rem .4rem; border: 1px solid var(--line);
border-radius: 4px; background: var(--bg); color: var(--fg); }
.notice { border: 1px solid var(--line); border-left: 3px solid var(--accent);
padding: .75rem 1rem; border-radius: 4px; color: var(--muted);
font-size: .9rem; max-width: 60ch; }
code { font-family: ui-monospace, SFMono-Regular, monospace; font-size: .9em; }
</style>
</head>
<body>
<header>
<h1>Enclave</h1>
<!-- The session label is chosen per request and sent as a header. Absent, the
server falls back to the clearance MINIMUM, never the maximum. -->
<div class="label-picker">
<label for="session-label">Working at</label>
<select id="session-label" disabled>
<option>sign in to choose a label</option>
</select>
</div>
</header>
<main>
<div class="notice">
Files and filenames are encrypted in your browser before upload. The server
stores ciphertext and enforces labels on the metadata it can see &mdash; the
shape of your tree, sizes, and timestamps. It cannot read names or contents.
<br><br>
Because this page&rsquo;s code is served by the same host that stores your
data, a compromised server could serve code that captures your keys. For a
guarantee that does not depend on trusting the host at load time, use a
signed native client.
</div>
<div id="browser" hidden></div>
</main>
<script type="module">
// Placeholder for the client crypto module. It unwraps label keys with an
// identity key derived from the user's passphrase, then decrypts filenames
// and content locally. Nothing on this page sends a passphrase anywhere.
//
// Wire this to the key hierarchy documented in ARCHITECTURE.md:
// identity key -> label key -> node key -> content key
const picker = document.getElementById('session-label');
picker.title = 'Sent as X-Enclave-Classification / X-Enclave-Compartments';
</script>
</body>
</html>
+58
View File
@@ -0,0 +1,58 @@
# Security
## Reporting
Report vulnerabilities privately to **security@extant2000.com**. Please do not
open a public issue for anything exploitable.
## What this system protects
- **Cross-tenant separation.** Enforced twice: separate OS processes, and
Postgres grants that give a tenant role `USAGE` on its own schema alone. A
logic bug in the label lattice cannot reach another tenant's data because the
grant is checked before any policy runs.
- **Label separation within a tenant.** Row-level security on every labeled
table, plus a key hierarchy in which a node's key is wrapped to its label key.
Both must fail for content to leak across labels.
- **Content confidentiality against the server.** Filenames and contents are
encrypted client side.
- **Inference control.** Undominated objects are reported as absent. Names are
polyinstantiated so constraint violations cannot confirm existence.
Deduplication is disabled and quota is per-label, both to close covert
channels.
## What it does not protect
- **The web client's supply chain.** The page's JavaScript is served by the
host that stores the data. A compromised or coerced server can serve
key-capturing code. This is inherent to browser-delivered end-to-end
encryption and is not solved here. A signed native client would address it;
none exists yet.
- **Metadata.** The server knows the shape of your tree, every node's label,
sizes, timestamps, and which principals hold which label keys. Traffic
analysis against that metadata is out of scope.
- **Clearance revocation.** Removing a compartment rotates the label key, but a
user who already held the old key keeps it. Content encrypted under the old
key stays readable to them until it is re-encrypted. There is no mechanism
today that forces re-encryption.
- **Compromised endpoints.** Keys are derived on the client from a passphrase.
Malware on that device defeats everything above.
- **Availability.** No rate limiting, no denial-of-service protection.
## Cryptographic posture
This project implements **no cryptographic primitives**. `EnclaveCrypto` defines
the key hierarchy's shape and its invariants; primitives are expected to come
from swift-crypto and from the audited engine in
[flamenet-e2e](https://gitlab.com/paulhitt/flamenet-e2e). Note that flamenet-e2e
is a messaging engine: its primitives transfer, its session model does not — a
Drive needs a key hierarchy, not a ratchet.
⚠️ **The client-side crypto is not implemented.** Nothing is encrypted today.
## Accreditation
Implementing a Bell-LaPadula-style model is not the same as being authorized to
hold classified information. This project has no ATO, has not been assessed
against NIST 800-53 or ICD 503, and makes no claim of suitability for classified
data. It implements the *model*, for commercial multi-tenancy.
+88
View File
@@ -0,0 +1,88 @@
# Self-hosting Enclave
## The one thing that will bite you
**The application must not connect to Postgres as a superuser or as the schema
owner.**
Postgres superusers bypass row-level security unconditionally. So does any role
holding `BYPASSRLS`. `FORCE ROW LEVEL SECURITY` does not help. If you point
`DATABASE_URL` at the `postgres` user — which is what most quick-start compose
files do — every policy in this project becomes inert, and *nothing looks
wrong*: queries return rows, the UI works, performance is fine, and every user
sees every file regardless of label.
`docker-compose.yml` therefore uses two roles:
| Role | Used by | Why |
|---|---|---|
| `enclave_owner` | the `migrate` service | installing policies, triggers and grants needs ownership |
| `tenant_<slug>` | the `app` service | plain role; RLS applies to it |
The server calls `RLSGuard.assertRowLevelSecurityApplies` at boot and refuses to
start if its own role can bypass RLS. Do not remove that check.
## Setup
```bash
cp .env.example .env
```
Generate each secret separately:
```bash
openssl rand -base64 36
```
Fill in `POSTGRES_PASSWORD`, `ENCLAVE_TENANT_PASSWORD`, and
`ENCLAVE_JWT_SECRET`. Then:
```bash
docker compose up --build
```
The `migrate` service runs once, installs the shared helpers and the tenant
schema, and exits. `app` starts only after it completes successfully.
## TLS
`ENCLAVE_BIND` defaults to `127.0.0.1`, so the app is not reachable from outside
the host as shipped. Put a TLS-terminating reverse proxy in front of it. Serving
this over plain HTTP defeats the client-side encryption entirely — an attacker
who can rewrite the page can replace the crypto.
## Tokens
The server verifies clearance tokens; it does not mint them. Your control plane
signs an `EnclaveToken` with `ENCLAVE_JWT_SECRET` containing the principal id,
tenant, and clearance bounds. Keep token lifetimes short: revoking a clearance
does not invalidate a token already issued.
Rotating `ENCLAVE_JWT_SECRET` invalidates every outstanding session.
## Adding a tenant
Each tenant is a schema, a role, and its own worker process. Set
`ENCLAVE_TENANT` and run the `migrate` service again; then run another `app`
container with that tenant's `DATABASE_URL`. Do not serve two tenants from one
process — the process boundary is half of the isolation.
## Backups
`enclave-pgdata` is a **named** volume. This is deliberate: an anonymous volume
is reported as "dangling" and a routine `docker volume prune` will destroy it,
along with every file your users have.
Back up with `pg_dump` from the owner role. Note that a dump contains all
ciphertext and all labels; it does not contain any key that opens the
ciphertext, since those exist only wrapped to user identity keys. Losing the
database loses the data; losing a user's passphrase loses that user's files
irrecoverably unless recovery phrases are implemented — they are not, yet.
## Upgrades
Migrations do not run on restart. Run the `migrate` service deliberately:
```bash
docker compose run --rm migrate
```
+89
View File
@@ -0,0 +1,89 @@
import EnclaveLattice
/// Access-mode and decision types. The point of this module is that the *shape*
/// of a denial is part of the return type: a read denial and a write denial must
/// not be reported to the caller the same way, or the error channel leaks the
/// existence of data the caller is not cleared to know about.
public enum AccessMode: Sendable, Hashable {
case read
case write
}
public enum Decision: Sendable, Hashable {
case allow
/// The object exists but the subject does not dominate it.
/// MUST surface as HTTP 404 with the same body as a genuinely missing
/// resource. A 403 here tells the caller that something is there.
case denyNotVisible
/// The subject can see the object but may not modify it at this session
/// label. Safe to surface as 403 — visibility is already established.
case denyReadOnly
/// The session label itself is outside the principal's clearance. This is a
/// bad request from an authenticated caller, not a data-dependent denial,
/// so it carries no information about any object. Safe as 403.
case denyOutsideClearance
}
/// How writes relate to the session label.
public enum WriteRule: Sendable, Hashable {
/// Write only at exactly the session label (strong tranquility). The default:
/// it makes every write auditable and rules out blind writes entirely.
case equal
/// Bell-LaPadula *-property: may write at or above the session label.
/// Permits blind write-up, which most commercial deployments do not want
/// because the writer cannot then read back what they just wrote.
case starProperty
}
public struct Policy: Sendable, Hashable {
public var writeRule: WriteRule
public init(writeRule: WriteRule = .equal) {
self.writeRule = writeRule
}
/// Decide a single access. `subject` is the *session* label, already
/// validated against the principal's clearance by `session(at:for:)`.
public func decide(subject: Label, object: Label, mode: AccessMode) -> Decision {
// Simple security property: no read up. Dominance is required for the
// object to be visible at all, so this gate comes first for every mode.
guard subject.dominates(object) else { return .denyNotVisible }
switch mode {
case .read:
return .allow
case .write:
switch writeRule {
case .equal:
return subject == object ? .allow : .denyReadOnly
case .starProperty:
// Reachable only when subject == object, since write-up objects
// failed the dominance gate above and are already .denyNotVisible.
return object.dominates(subject) ? .allow : .denyReadOnly
}
}
}
/// Validate a requested session label against a principal's clearance.
/// Call this once at authentication; every later decision assumes it passed.
public func session(at label: Label, for clearance: Clearance) -> Decision {
clearance.permits(label) ? .allow : .denyOutsideClearance
}
}
extension Decision {
/// The HTTP status a denial must be reported as. Centralised so no handler
/// can independently decide to be "more helpful" than the policy allows.
public var httpStatus: Int {
switch self {
case .allow: 200
case .denyNotVisible: 404
case .denyReadOnly, .denyOutsideClearance: 403
}
}
}
+94
View File
@@ -0,0 +1,94 @@
import Foundation
import EnclaveLattice
import EnclaveCrypto
/// Rules for a labeled file hierarchy.
///
/// A directory tree is the hardest structure to label correctly, because a node
/// is only reachable through its ancestors. Two rules fall out of that, and both
/// are enforced here and again as database constraints.
public struct Node: Sendable, Hashable, Identifiable {
public let id: UUID
public let parentID: UUID?
public let name: NameDigest
public let label: Label
public let isFolder: Bool
public init(id: UUID, parentID: UUID?, name: NameDigest, label: Label, isFolder: Bool) {
self.id = id
self.parentID = parentID
self.name = name
self.label = label
self.isFolder = isFolder
}
}
public enum TreeViolation: Error, Sendable, Hashable {
/// A child whose label its parent's label does not sit below would be
/// unreachable: anyone cleared for the child could not traverse the parent.
case childDoesNotDominateParent(child: Label, parent: Label)
}
public enum Resolution: Sendable, Hashable {
case found(UUID)
/// No entry of that name is visible at this session label. Report as 404 —
/// indistinguishable from a name that exists at a label you cannot see.
case notVisible
/// Several visible entries share the name at mutually incomparable labels
/// and none matches the session label exactly. The caller must disambiguate
/// explicitly rather than have the server guess.
case ambiguous([UUID])
}
public enum Tree {
/// Invariant: every child's label dominates its parent's.
///
/// Note this permits a SECRET file inside a CONFIDENTIAL folder (the usual
/// case) and forbids the inverse, which would strand the child.
public static func validate(child: Label, parent: Label) throws {
guard child.dominates(parent) else {
throw TreeViolation.childDoesNotDominateParent(child: child, parent: parent)
}
}
/// The label a newly created node takes.
///
/// Under `WriteRule.equal` this is just the session label, and the tree
/// invariant is then automatic: the session could only traverse into the
/// parent by dominating it, so session ⊒ parent already holds.
public static func labelForNewNode(session: Label, parent: Label) -> Label {
Label.leastUpperBound(session, parent)
}
/// Entries of a folder visible at `session`, as a listing would show them.
public static func visibleChildren(of children: [Node], at session: Label) -> [Node] {
children.filter { session.dominates($0.label) }
}
/// Resolve one path component within a folder, honouring polyinstantiation:
/// the same name may exist at several labels, and each session sees its own.
public static func resolve(
name: NameDigest,
among children: [Node],
at session: Label
) -> Resolution {
let visible = children.filter { $0.name == name && session.dominates($0.label) }
if visible.isEmpty { return .notVisible }
// An exact label match always wins — that is the caller's own instance.
if let exact = visible.first(where: { $0.label == session }) {
return .found(exact.id)
}
// Otherwise take the unique most-sensitive visible instance, if there is
// one. Incomparable candidates have no defensible winner.
let maximal = visible.filter { candidate in
!visible.contains { $0.id != candidate.id && $0.label.dominates(candidate.label) }
}
if maximal.count == 1 { return .found(maximal[0].id) }
return .ambiguous(maximal.map(\.id))
}
}
+126
View File
@@ -0,0 +1,126 @@
import Foundation
import EnclaveLattice
/// The key hierarchy for zero-knowledge storage.
///
/// This module defines the *shape* of the hierarchy and the invariants that
/// keep it aligned with the lattice. It deliberately implements no primitives:
/// KEM, AEAD and KDF come from swift-crypto and the audited core in
/// `flamenet-e2e`. Inventing them here would be the single worst decision
/// available in this codebase.
///
/// ## The rule
///
/// **A node's key is wrapped to its LABEL key, never to its parent's key.**
///
/// The obvious Drive design derives each node key from its parent folder's key.
/// That is wrong here. The tree invariant permits a RESTRICTED file inside a
/// CONFIDENTIAL folder, so parent-derived keys would hand every holder of the
/// folder key the ability to decrypt content above their clearance. Row-level
/// security would still refuse to *serve* the ciphertext, but anyone with a
/// backup, a snapshot, or a compromised server would read it. Crypto must
/// enforce the lattice independently, or it quietly cancels it.
///
/// ## Three levels
///
/// ```
/// identity key per user, derived from passphrase; never leaves client
/// │ wraps
/// label key one per label actually in use in the tenant
/// │ wraps (wrapped to every user whose clearance permits it)
/// node key one per file/folder, random
/// │ wraps
/// content key one per revision
/// ```
///
/// Labels in use are dozens, not 2^64: keys are materialised on first use at a
/// label and wrapped to the cleared population then.
/// An opaque handle to a key held only in wrapped form on the server.
public struct WrappedKey: Hashable, Sendable, Codable {
public let ciphertext: Data
/// The key this blob is wrapped *to*, so a client knows what to unwrap with.
public let wrappedTo: KeyRef
public init(ciphertext: Data, wrappedTo: KeyRef) {
self.ciphertext = ciphertext
self.wrappedTo = wrappedTo
}
}
public enum KeyRef: Hashable, Sendable, Codable {
case identity(principalID: UUID)
case label(Label)
case node(UUID)
}
/// A label key, materialised on first use and wrapped to each cleared principal.
public struct LabelKeyGrant: Hashable, Sendable, Codable {
public let label: Label
public let principalID: UUID
public let wrapped: WrappedKey
/// Bumped when the label key rotates, which is what revocation triggers.
public let generation: Int
public init(label: Label, principalID: UUID, wrapped: WrappedKey, generation: Int) {
self.label = label
self.principalID = principalID
self.wrapped = wrapped
self.generation = generation
}
}
public enum KeyHierarchyError: Error, Sendable, Hashable {
/// A node key wrapped to anything other than its own label's key. This is
/// the mistake the whole module exists to prevent.
case nodeKeyNotWrappedToItsLabel(node: UUID, expected: Label, actual: KeyRef)
/// A label key granted to a principal whose clearance does not permit it.
case grantExceedsClearance(label: Label, principalID: UUID)
}
public enum KeyHierarchy {
/// Check that a node's key is wrapped to its own label key.
/// Call on every node-key write; it is cheap and it is the invariant.
public static func validate(nodeID: UUID, nodeLabel: Label, key: WrappedKey) throws {
guard case .label(let wrappedLabel) = key.wrappedTo, wrappedLabel == nodeLabel else {
throw KeyHierarchyError.nodeKeyNotWrappedToItsLabel(
node: nodeID, expected: nodeLabel, actual: key.wrappedTo
)
}
}
/// Check that a label key is only ever granted within a clearance.
public static func validate(grant: LabelKeyGrant, clearance: Clearance) throws {
guard clearance.permits(grant.label) else {
throw KeyHierarchyError.grantExceedsClearance(
label: grant.label, principalID: grant.principalID
)
}
}
}
/// Server-side name matching without server-side name knowledge.
///
/// Filenames are ciphertext, and encryption must be randomised, so two
/// encryptions of "Payroll" differ and no uniqueness constraint can see them as
/// equal. Uniqueness and lookup therefore run on a deterministic digest:
///
/// digest = HMAC(folder_key, normalise(name))
///
/// Keyed with the folder key so the server cannot correlate names across
/// folders, cannot dictionary-attack them, and cannot invert them.
///
/// The existence oracle stays closed because the unique index also spans the
/// label: a low-cleared user inserting a colliding digest at their own label
/// never touches the higher-labeled row.
public struct NameDigest: Hashable, Sendable, Codable {
public let bytes: Data
/// For a zero-knowledge deployment: the HMAC computed on the client.
public init(hmac: Data) { self.bytes = hmac }
/// For a server-readable deployment, or for tests.
public init(plaintext: String) {
self.bytes = Data(plaintext.precomposedStringWithCanonicalMapping.utf8)
}
}
+136
View File
@@ -0,0 +1,136 @@
/// The security lattice: a classification (hierarchical) crossed with a set of
/// compartments (non-hierarchical). Ordering is *partial*, not total — two labels
/// can be mutually incomparable, and every access decision must handle that case.
/// A hierarchical sensitivity level, stored as an ordinal so tenants can name
/// their own ladder (Public/Internal/Confidential/Restricted, or U/C/S/TS).
/// Only the ordering is meaningful here; display names live in the control plane.
public struct Classification: RawRepresentable, Hashable, Sendable, Comparable, Codable {
public let rawValue: Int16
public init(rawValue: Int16) { self.rawValue = rawValue }
public init(_ rawValue: Int16) { self.rawValue = rawValue }
public static func < (lhs: Self, rhs: Self) -> Bool { lhs.rawValue < rhs.rawValue }
/// The bottom of every tenant's ladder. Ordinals are dense and start at zero.
public static let lowest = Classification(rawValue: 0)
public init(from decoder: any Decoder) throws {
rawValue = try decoder.singleValueContainer().decode(Int16.self)
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(rawValue)
}
}
/// A non-hierarchical set of need-to-know markers, held as a 64-bit vector so
/// dominance is a single integer AND both here and in the Postgres predicate.
/// Bit positions are assigned per tenant in `enclave_control.compartments`.
public struct Compartments: OptionSet, Hashable, Sendable, Codable {
public var rawValue: UInt64
public init(rawValue: UInt64) { self.rawValue = rawValue }
/// - Parameter bits: compartment bit positions, each in `0...63`.
public init(bits: some Sequence<Int>) {
var value: UInt64 = 0
for bit in bits {
precondition((0...63).contains(bit), "compartment bit \(bit) out of range")
value |= (1 << UInt64(bit))
}
self.rawValue = value
}
public static let empty = Compartments([])
/// The bit positions currently set, ascending.
public var bits: [Int] { (0...63).filter { rawValue & (1 << UInt64($0)) != 0 } }
// Encoded as an array of bit positions rather than the raw integer: a 64-bit
// mask exceeds JSON's exact-integer range and would silently round-trip wrong.
public init(from decoder: any Decoder) throws {
self.init(bits: try decoder.singleValueContainer().decode([Int].self))
}
public func encode(to encoder: any Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(bits)
}
}
/// A point in the lattice. Attached to every labeled row and to every session.
public struct Label: Hashable, Sendable, Codable {
public var classification: Classification
public var compartments: Compartments
public init(classification: Classification, compartments: Compartments = .empty) {
self.classification = classification
self.compartments = compartments
}
/// The lattice bottom: lowest classification, no compartments.
public static let bottom = Label(classification: .lowest, compartments: .empty)
/// `self ⊒ other` — self is at least as sensitive on *both* axes.
/// This is the only comparison an access decision may use.
public func dominates(_ other: Label) -> Bool {
classification >= other.classification
&& compartments.isSuperset(of: other.compartments)
}
/// True when neither label dominates the other. Distinct from "less than":
/// `SECRET//NOFORN` and `TOP SECRET//SI` are incomparable, not ordered.
public func isIncomparable(to other: Label) -> Bool {
!dominates(other) && !other.dominates(self)
}
/// Least upper bound — the cheapest label that can hold both inputs.
/// This is the correct label for a record derived from two sources.
public static func leastUpperBound(_ lhs: Label, _ rhs: Label) -> Label {
Label(
classification: max(lhs.classification, rhs.classification),
compartments: lhs.compartments.union(rhs.compartments)
)
}
/// Greatest lower bound — the most sensitive label both inputs dominate.
public static func greatestLowerBound(_ lhs: Label, _ rhs: Label) -> Label {
Label(
classification: min(lhs.classification, rhs.classification),
compartments: lhs.compartments.intersection(rhs.compartments)
)
}
}
/// What a principal is *allowed* to assert. A session picks one label from this
/// range; it is not a total-order interval, since labels incomparable to the
/// maximum are excluded by the dominance test rather than by any numeric bound.
public struct Clearance: Hashable, Sendable, Codable {
public var maximum: Label
public var minimum: Label
public init(maximum: Label, minimum: Label = .bottom) {
self.maximum = maximum
self.minimum = minimum
}
/// Whether a principal holding this clearance may run a session at `label`.
public func permits(_ label: Label) -> Bool {
maximum.dominates(label) && label.dominates(minimum)
}
}
extension Compartments {
/// Postgres has no unsigned 64-bit integer, so the mask is stored as a
/// signed `bigint`. Bit 63 makes that value negative; a checked conversion
/// would trap and an unchecked one would be easy to get wrong by accident,
/// so the reinterpretation is spelled out here and used on both edges.
public var postgresBitPattern: Int64 { Int64(bitPattern: rawValue) }
public init(postgresBitPattern: Int64) {
self.init(rawValue: UInt64(bitPattern: postgresBitPattern))
}
}
@@ -0,0 +1,59 @@
import Foundation
import JWT
import Vapor
import EnclaveLattice
/// Clearance travels in a signed token, not in a database lookup.
///
/// A tenant worker holds a role with `USAGE` on its own schema only -- it cannot
/// read `enclave_control.principals`, and that is the point. The control plane
/// authenticates the user, reads their clearance once, and mints this token. The
/// worker verifies the signature and trusts the claims. No worker ever needs
/// credentials that reach across the tenant boundary.
struct EnclaveToken: JWTPayload {
enum CodingKeys: String, CodingKey {
case subject = "sub"
case expiration = "exp"
case tenant = "ten"
case maxClassification = "mxc"
case maxCompartments = "mxk"
case minClassification = "mnc"
case minCompartments = "mnk"
}
var subject: SubjectClaim
var expiration: ExpirationClaim
var tenant: String
// Clearance bounds, flattened so the token stays small.
var maxClassification: Int16
var maxCompartments: Int64
var minClassification: Int16
var minCompartments: Int64
func verify(using algorithm: some JWTAlgorithm) async throws {
try expiration.verifyNotExpired()
}
var principalID: UUID {
get throws {
guard let id = UUID(uuidString: subject.value) else {
throw Abort(.unauthorized, reason: "token subject is not a principal id")
}
return id
}
}
var clearance: Clearance {
Clearance(
maximum: Label(
classification: Classification(maxClassification),
compartments: Compartments(postgresBitPattern: maxCompartments)
),
minimum: Label(
classification: Classification(minClassification),
compartments: Compartments(postgresBitPattern: minCompartments)
)
)
}
}
@@ -0,0 +1,93 @@
import Foundation
import JWT
import Vapor
import EnclaveLattice
import EnclaveAccess
/// Everything a request is allowed to do, resolved once at the edge.
struct SessionContext: Sendable {
let principalID: UUID
let clearance: Clearance
/// Already validated against `clearance`. Downstream code may use it freely.
let label: Label
}
private struct SessionContextKey: StorageKey {
typealias Value = SessionContext
}
extension Request {
var session: SessionContext {
get throws {
guard let context = storage[SessionContextKey.self] else {
throw Abort(.unauthorized, reason: "no session label established")
}
return context
}
}
fileprivate func setSession(_ context: SessionContext) {
storage[SessionContextKey.self] = context
}
}
/// Verifies the token, resolves the requested session label, and refuses
/// anything the principal's clearance does not permit.
struct EnclaveSessionMiddleware: AsyncMiddleware {
static let classificationHeader = "X-Enclave-Classification"
static let compartmentsHeader = "X-Enclave-Compartments"
let policy: Policy
func respond(to request: Request, chainingTo next: any AsyncResponder) async throws -> Response {
let token = try await request.jwt.verify(as: EnclaveToken.self)
let clearance = token.clearance
let requested = try Self.requestedLabel(in: request, defaultingTo: clearance.minimum)
// A label outside the clearance is refused here, once, so that no
// downstream code has to re-derive what the principal may assert.
guard policy.session(at: requested, for: clearance) == .allow else {
throw Abort(.forbidden, reason: "session label exceeds clearance")
}
request.setSession(
SessionContext(
principalID: try token.principalID,
clearance: clearance,
label: requested
)
)
return try await next.respond(to: request)
}
/// Absent headers default to the clearance *minimum*, never the maximum.
/// A client that forgets to declare a label gets the least sensitive
/// session it could have asked for rather than the most.
static func requestedLabel(in request: Request, defaultingTo fallback: Label) throws -> Label {
guard let raw = request.headers.first(name: classificationHeader) else {
return fallback
}
guard let classification = Int16(raw) else {
throw Abort(.badRequest, reason: "\(classificationHeader) must be an integer ordinal")
}
let bits = (request.headers.first(name: compartmentsHeader) ?? "")
.split(separator: ",")
.map(String.init)
.compactMap { $0.trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
var positions: [Int] = []
for bit in bits {
guard let position = Int(bit), (0...63).contains(position) else {
throw Abort(.badRequest, reason: "compartment bit '\(bit)' is not in 0...63")
}
positions.append(position)
}
return Label(
classification: Classification(classification),
compartments: Compartments(bits: positions)
)
}
}
@@ -0,0 +1,64 @@
import Fluent
import Vapor
import Foundation
import EnclaveLattice
/// Key distribution.
///
/// Everything here is wrapped ciphertext. The server hands out blobs it cannot
/// open, and the client unwraps them with an identity key derived from a
/// passphrase that never leaves the device.
struct KeyController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let keys = routes.grouped("api", "keys")
keys.get("labels", use: labelGrants)
keys.get("nodes", ":nodeID", use: nodeKey)
}
struct GrantResponse: Content {
let classification: Int16
let compartments: [Int]
let generation: Int
let wrappedKey: Data
}
/// The label keys wrapped to the calling principal.
///
/// Filtered by principal rather than by dominance: which *other* people hold
/// a compartment is itself sensitive, so this is not a lattice query.
func labelGrants(request: Request) async throws -> [GrantResponse] {
let session = try request.session
return try await request.labeled { db in
try await LabelKeyGrantModel.query(on: db)
.filter(\.$principalID == session.principalID)
.all()
.map {
GrantResponse(
classification: $0.classification,
compartments: $0.label.compartments.bits,
generation: $0.generation,
wrappedKey: $0.wrappedKey
)
}
}
}
/// One node's wrapped key. RLS hides keys above the session label, so an
/// undominated node's key is a 404 exactly like the node itself.
func nodeKey(request: Request) async throws -> GrantResponse {
guard let nodeID = request.parameters.get("nodeID", as: UUID.self) else {
throw Abort(.badRequest, reason: "nodeID must be a uuid")
}
return try await request.labeled { db in
guard let key = try await NodeKeyModel.find(nodeID, on: db) else {
throw Abort(.notFound)
}
return GrantResponse(
classification: key.classification,
compartments: key.label.compartments.bits,
generation: key.generation,
wrappedKey: key.wrappedKey
)
}
}
}
@@ -0,0 +1,132 @@
import Fluent
import Vapor
import Foundation
import EnclaveLattice
import EnclaveAccess
import EnclaveCrypto
/// File-tree routes.
///
/// Note how little access-control code appears here. Row-level security filters
/// below the ORM, so an undominated node simply is not returned, and the
/// ordinary `guard let ... else { throw Abort(.notFound) }` is already the
/// correct inference-controlled answer. Handlers that reach for `Policy`
/// directly are the exception, not the rule.
struct NodeController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let nodes = routes.grouped("api", "nodes")
nodes.get(":folderID", "children", use: children)
nodes.post(use: create)
}
// MARK: responses
struct NodeResponse: Content {
let id: UUID
let isFolder: Bool
let classification: Int16
let compartments: [Int]
let nameCiphertext: Data
let sizeBytes: Int64
}
struct CreateNodeRequest: Content {
let parentID: UUID?
let nameDigest: Data
let nameCiphertext: Data
let isFolder: Bool
/// The node key, already wrapped client-side to the session label's key.
let wrappedKey: Data
let sizeBytes: Int64?
}
// MARK: handlers
/// List a folder's visible children.
func children(request: Request) async throws -> [NodeResponse] {
guard let folderID = request.parameters.get("folderID", as: UUID.self) else {
throw Abort(.badRequest, reason: "folderID must be a uuid")
}
return try await request.labeled { db in
// The folder itself must be visible, or the listing would confirm
// the existence of a folder the caller cannot see.
guard try await NodeModel.find(folderID, on: db) != nil else {
throw Abort(.notFound)
}
let visible = try await NodeModel.query(on: db)
.filter(\.$parentID == folderID)
.all()
return visible.map {
NodeResponse(
id: $0.id!,
isFolder: $0.isFolder,
classification: $0.classification,
compartments: $0.label.compartments.bits,
nameCiphertext: $0.nameCiphertext,
sizeBytes: $0.sizeBytes
)
}
}
}
/// Create a file or folder, with its wrapped key, atomically.
func create(request: Request) async throws -> Response {
let session = try request.session
let input = try request.content.decode(CreateNodeRequest.self)
let node = NodeModel(
parentID: input.parentID,
nameDigest: input.nameDigest,
nameCiphertext: input.nameCiphertext,
isFolder: input.isFolder,
label: session.label,
createdBy: session.principalID,
sizeBytes: input.sizeBytes ?? 0
)
// Checked here as well as by the database trigger. The trigger is the
// real guarantee; this exists so the failure arrives as a typed Swift
// error with a usable message rather than a raw constraint violation.
try KeyHierarchy.validate(
nodeID: node.id ?? UUID(),
nodeLabel: session.label,
key: WrappedKey(ciphertext: input.wrappedKey, wrappedTo: .label(session.label))
)
return try await request.labeled { db in
// One transaction: a node without its key is unopenable, and a key
// without its node is a dangling secret.
try await node.create(on: db)
let key = NodeKeyModel(
nodeID: try node.requireID(),
label: session.label,
wrappedKey: input.wrappedKey
)
try await key.create(on: db)
try await AuditEntry(
actorID: session.principalID,
sessionLabel: session.label,
action: "node.create",
nodeID: try node.requireID(),
label: session.label
).write(on: db)
let response = Response(status: .created)
try response.content.encode(
NodeResponse(
id: try node.requireID(),
isFolder: node.isFolder,
classification: node.classification,
compartments: node.label.compartments.bits,
nameCiphertext: node.nameCiphertext,
sizeBytes: node.sizeBytes
)
)
return response
}
}
}
@@ -0,0 +1,34 @@
import Fluent
import SQLKit
import Foundation
import EnclaveLattice
/// An append-only audit record.
///
/// Written through raw SQL rather than a Fluent model on purpose: the table has
/// no UPDATE or DELETE grant, and modelling it as a mutable entity would invite
/// code that assumes otherwise. Audit rows carry the label of the thing they
/// describe, so the log cannot become the leak.
struct AuditEntry {
let actorID: UUID
let sessionLabel: Label
let action: String
let nodeID: UUID?
let label: Label
var detail: String = "{}"
func write(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
let session = sessionLabel.columns
let object = label.columns
try await sql.raw("""
INSERT INTO audit_log
(actor_id, session_class, session_comp, action,
node_id, classification, compartments, detail)
VALUES
(\(bind: actorID), \(bind: session.classification), \(bind: session.compartments),
\(bind: action), \(bind: nodeID), \(bind: object.classification),
\(bind: object.compartments), \(bind: detail)::jsonb)
""").run()
}
}
@@ -0,0 +1,52 @@
import Fluent
import SQLKit
import Vapor
import EnclaveLattice
/// The only sanctioned path to the database.
///
/// Every query must run inside a transaction that has pinned the session label
/// into transaction-local settings, because that is what the RLS policies read.
/// Three things make this correct:
///
/// 1. `SET LOCAL` semantics are transaction-scoped, so a pooled connection
/// cannot carry one user's label into another user's request.
/// 2. `set_config(name, value, true)` is the parameterisable form. `SET LOCAL`
/// itself takes no bind parameters, so building it by interpolation would be
/// an injection site; this avoids that entirely.
/// 3. Forgetting the label fails closed -- unset settings read as NULL, every
/// dominance test evaluates to NULL, and RLS treats NULL as false. But the
/// symptom is an empty result set rather than an error, which is a miserable
/// thing to debug, so `session` throws if the middleware never ran.
extension Request {
func labeled<T>(_ body: @escaping @Sendable (any Database) async throws -> T) async throws -> T
where T: Sendable {
let session = try self.session
return try await self.db.transaction { database in
guard let sql = database as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "labeled access requires a SQL database")
}
try await sql.raw("""
SELECT set_config('enclave.classification', \(bind: String(session.label.classification.rawValue)), true),
set_config('enclave.compartments', \(bind: String(session.label.compartments.postgresBitPattern)), true),
set_config('enclave.principal', \(bind: session.principalID.uuidString), true)
""").run()
return try await body(database)
}
}
}
extension Label {
/// Split form for storage. Kept next to the wrapper so the two encodings of
/// a label -- GUC and column -- never drift apart.
var columns: (classification: Int16, compartments: Int64) {
(classification.rawValue, compartments.postgresBitPattern)
}
init(classification: Int16, compartments: Int64) {
self.init(
classification: Classification(classification),
compartments: Compartments(postgresBitPattern: compartments)
)
}
}
@@ -0,0 +1,52 @@
import Fluent
import SQLKit
import Vapor
/// Refuse to serve traffic on a connection that can ignore row-level security.
///
/// This is the single most dangerous misconfiguration available to a
/// self-hoster. Postgres superusers bypass RLS unconditionally, and so does any
/// role holding BYPASSRLS -- FORCE ROW LEVEL SECURITY does not save you. The
/// failure is silent and looks exactly like everything working: queries return
/// rows, the app is fast, and every label is being ignored.
///
/// Pointing DATABASE_URL at the postgres superuser is the obvious way to get
/// here, and it is what most quick-start compose files do. So the server checks
/// its own role at boot and refuses rather than serving unlabelled data.
enum RLSGuard {
private struct RoleFacts: Decodable {
let is_superuser: Bool
let bypasses_rls: Bool
let role_name: String
}
static func assertRowLevelSecurityApplies(_ app: Application) async throws {
guard let sql = app.db as? any SQLDatabase else {
throw Abort(.internalServerError, reason: "expected a SQL database")
}
let facts = try await sql.raw("""
SELECT current_user::text AS role_name,
current_setting('is_superuser') = 'on' AS is_superuser,
COALESCE((SELECT rolbypassrls FROM pg_roles
WHERE rolname = current_user), false) AS bypasses_rls
""").first(decoding: RoleFacts.self)
guard let facts else {
throw Abort(.internalServerError, reason: "could not determine database role")
}
if facts.is_superuser || facts.bypasses_rls {
let why = facts.is_superuser ? "is a superuser" : "holds BYPASSRLS"
app.logger.critical("""
Refusing to start: database role '\(facts.role_name)' \(why), so every \
row-level security policy is ignored and labels are not enforced. Point \
DATABASE_URL at the per-tenant role (tenant_<slug>) instead of the owner \
or superuser. See SELF-HOSTING.md.
""")
throw Abort(.internalServerError, reason: "database role can bypass row-level security")
}
app.logger.info("row-level security applies to role '\(facts.role_name)'")
}
}
@@ -0,0 +1,95 @@
import Fluent
import SQLKit
import Foundation
import Vapor
/// Schema installation.
///
/// Fluent's schema builder cannot express row-level security policies, FORCE
/// ROW LEVEL SECURITY, triggers, or grants -- which is most of what protects
/// this system. So the DDL lives in .sql files and these migrations execute it
/// verbatim. Wrapping it in Fluent migrations rather than shelling out to psql
/// keeps `_fluent_migrations` as the version record, and because each tenant
/// has its own search_path that record lands per-tenant automatically.
enum TenantSchema {
/// Slugs become schema and role identifiers, which cannot be parameterised
/// in DDL. Validate rather than escape: anything outside this alphabet is
/// rejected instead of quoted.
static func validate(slug: String) throws {
let allowed = Set("abcdefghijklmnopqrstuvwxyz0123456789_")
guard (2...39).contains(slug.count),
let first = slug.first, first.isLowercase, first.isLetter,
slug.allSatisfy(allowed.contains)
else {
throw Abort(.badRequest, reason: "tenant slug '\(slug)' is not a safe identifier")
}
}
static func sql(named name: String) throws -> String {
guard let url = Bundle.module.url(forResource: "SQL/\(name)", withExtension: "sql") else {
throw Abort(.internalServerError, reason: "missing bundled SQL resource \(name).sql")
}
return try String(contentsOf: url, encoding: .utf8)
}
}
/// Installs the shared `enclave` helpers and the control-plane registry.
struct InstallSharedSchema: AsyncMigration {
var name: String { "InstallSharedSchema" }
func prepare(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
try await sql.raw(.init(try TenantSchema.sql(named: "001_shared"))).run()
}
func revert(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
try await sql.raw("DROP SCHEMA IF EXISTS enclave CASCADE").run()
try await sql.raw("DROP SCHEMA IF EXISTS enclave_control CASCADE").run()
}
}
/// Installs one tenant's schema, policies, and grants.
struct InstallTenantSchema: AsyncMigration {
let slug: String
var name: String { "InstallTenantSchema.\(slug)" }
private var schemaName: String { "t_\(slug)" }
private var roleName: String { "tenant_\(slug)" }
func prepare(on database: any Database) async throws {
try TenantSchema.validate(slug: slug)
guard let sql = database as? any SQLDatabase else { return }
// The role must exist before the template's GRANTs run.
try await sql.raw("SELECT enclave.ensure_role(\(bind: roleName))").run()
let template = try TenantSchema.sql(named: "002_tenant_template")
.replacingOccurrences(of: ":schema", with: "\"\(schemaName)\"")
.replacingOccurrences(of: ":role", with: "\"\(roleName)\"")
try await sql.raw(.init(template)).run()
// With this set, the worker process never names its own schema: Fluent
// models declare plain table names and resolve into the right one.
try await sql.raw("""
ALTER ROLE \(unsafeRaw: "\"\(roleName)\"")
SET search_path = \(unsafeRaw: "\"\(schemaName)\""), enclave
""").run()
// The worker connects as this role, so it needs LOGIN. Deliberately not
// a superuser and never granted BYPASSRLS: both would make every policy
// installed above inert. `assertRowLevelSecurityApplies` checks at boot.
if let password = Environment.get("ENCLAVE_TENANT_PASSWORD"), !password.isEmpty {
try await sql.raw(
"SELECT enclave.set_role_login(\(bind: roleName), \(bind: password))"
).run()
}
}
func revert(on database: any Database) async throws {
try TenantSchema.validate(slug: slug)
guard let sql = database as? any SQLDatabase else { return }
try await sql.raw("DROP SCHEMA IF EXISTS \(unsafeRaw: "\"\(schemaName)\"") CASCADE").run()
}
}
@@ -0,0 +1,90 @@
import Fluent
import Foundation
import EnclaveLattice
/// A file or folder.
///
/// Table names are unqualified: the tenant role's search_path resolves them
/// into that tenant's schema, so nothing here is tenant-aware.
final class NodeModel: Model, @unchecked Sendable {
static let schema = "nodes"
@ID(key: .id) var id: UUID?
@OptionalField(key: "parent_id") var parentID: UUID?
/// HMAC(folder_key, normalise(name)), computed client-side. The server
/// never sees a filename in the clear.
@Field(key: "name_digest") var nameDigest: Data
@Field(key: "name_ciphertext") var nameCiphertext: Data
@Field(key: "is_folder") var isFolder: Bool
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@OptionalField(key: "blob_id") var blobID: UUID?
@Field(key: "size_bytes") var sizeBytes: Int64
@Field(key: "created_by") var createdBy: UUID
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
@Timestamp(key: "updated_at", on: .update) var updatedAt: Date?
@Timestamp(key: "deleted_at", on: .delete) var deletedAt: Date?
init() {}
init(parentID: UUID?, nameDigest: Data, nameCiphertext: Data,
isFolder: Bool, label: Label, createdBy: UUID, sizeBytes: Int64 = 0) {
self.parentID = parentID
self.nameDigest = nameDigest
self.nameCiphertext = nameCiphertext
self.isFolder = isFolder
(self.classification, self.compartments) = label.columns
self.createdBy = createdBy
self.sizeBytes = sizeBytes
}
var label: Label {
Label(classification: classification, compartments: compartments)
}
}
/// A node's content key, wrapped to its LABEL key.
final class NodeKeyModel: Model, @unchecked Sendable {
static let schema = "node_keys"
@ID(custom: "node_id", generatedBy: .user) var id: UUID?
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Field(key: "generation") var generation: Int
@Field(key: "wrapped_key") var wrappedKey: Data
init() {}
init(nodeID: UUID, label: Label, wrappedKey: Data, generation: Int = 1) {
self.id = nodeID
(self.classification, self.compartments) = label.columns
self.wrappedKey = wrappedKey
self.generation = generation
}
var label: Label {
Label(classification: classification, compartments: compartments)
}
}
/// A label key wrapped to one principal's identity key.
final class LabelKeyGrantModel: Model, @unchecked Sendable {
static let schema = "label_key_grants"
@ID(key: .id) var id: UUID?
@Field(key: "classification") var classification: Int16
@Field(key: "compartments") var compartments: Int64
@Field(key: "principal_id") var principalID: UUID
@Field(key: "generation") var generation: Int
@Field(key: "wrapped_key") var wrappedKey: Data
@Timestamp(key: "granted_at", on: .create) var grantedAt: Date?
init() {}
var label: Label {
Label(classification: classification, compartments: compartments)
}
}
+103
View File
@@ -0,0 +1,103 @@
-- Shared objects. Installed once per database, owned by enclave_owner.
-- Tenant workers get EXECUTE on the helpers and nothing else here.
CREATE SCHEMA IF NOT EXISTS enclave;
CREATE SCHEMA IF NOT EXISTS enclave_control;
-- Session label, read from transaction-local GUCs.
--
-- The `true` second argument makes a missing setting return NULL rather than
-- raise. NULL then makes every dominance test NULL, which RLS treats as false:
-- a worker that forgets to set its session label sees zero rows. Fail-closed by
-- construction, but it does mean "empty result set" is the symptom of a wiring
-- bug -- the Vapor middleware asserts the GUCs are present for that reason.
CREATE OR REPLACE FUNCTION enclave.session_classification() RETURNS smallint
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('enclave.classification', true), '')::smallint $$;
CREATE OR REPLACE FUNCTION enclave.session_compartments() RETURNS bigint
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('enclave.compartments', true), '')::bigint $$;
-- A ⊒ B: at least as high on the ladder AND a superset of compartments.
-- Compartments are a signed bigint here; bit 63 makes the value negative, which
-- is harmless because `&` is a pure bit operation. The Swift side must convert
-- with Int64(bitPattern:) rather than a checked cast.
CREATE OR REPLACE FUNCTION enclave.dominates(
subject_class smallint, subject_comp bigint,
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
$$ SELECT subject_class >= object_class AND (subject_comp & object_comp) = object_comp $$;
-- Convenience wrapper used by every read policy.
CREATE OR REPLACE FUNCTION enclave.session_dominates(
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql STABLE AS
$$ SELECT enclave.dominates(
enclave.session_classification(), enclave.session_compartments(),
object_class, object_comp) $$;
CREATE OR REPLACE FUNCTION enclave.session_label_is(
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql STABLE AS
$$ SELECT enclave.session_classification() = object_class
AND enclave.session_compartments() = object_comp $$;
-- Control plane. Lives outside every tenant schema; tenant roles cannot read it.
CREATE TABLE IF NOT EXISTS enclave_control.tenants (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
slug text UNIQUE NOT NULL CHECK (slug ~ '^[a-z][a-z0-9-]{1,38}$'),
schema_name text UNIQUE NOT NULL,
db_role text UNIQUE NOT NULL,
status text NOT NULL DEFAULT 'provisioning',
created_at timestamptz NOT NULL DEFAULT now()
);
-- Tenants name their own ladder; the lattice code only sees ordinals.
CREATE TABLE IF NOT EXISTS enclave_control.classification_levels (
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
ordinal smallint NOT NULL CHECK (ordinal >= 0),
name text NOT NULL,
PRIMARY KEY (tenant_id, ordinal),
UNIQUE (tenant_id, name)
);
CREATE TABLE IF NOT EXISTS enclave_control.compartments (
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
bit smallint NOT NULL CHECK (bit BETWEEN 0 AND 63),
name text NOT NULL,
PRIMARY KEY (tenant_id, bit),
UNIQUE (tenant_id, name)
);
CREATE TABLE IF NOT EXISTS enclave_control.principals (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
email text NOT NULL,
max_class smallint NOT NULL,
max_comp bigint NOT NULL DEFAULT 0,
min_class smallint NOT NULL DEFAULT 0,
min_comp bigint NOT NULL DEFAULT 0,
UNIQUE (tenant_id, email)
);
-- Role management. DDL cannot take bind parameters, so these wrap format()'s
-- %I/%L quoting -- the identifier and the password are escaped by Postgres
-- rather than by string-building in the application.
CREATE OR REPLACE FUNCTION enclave.ensure_role(role_name text) RETURNS void
LANGUAGE plpgsql AS
$fn$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = role_name) THEN
EXECUTE format('CREATE ROLE %I NOLOGIN', role_name);
END IF;
END
$fn$;
CREATE OR REPLACE FUNCTION enclave.set_role_login(role_name text, role_password text)
RETURNS void LANGUAGE plpgsql AS
$fn$
BEGIN
EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', role_name, role_password);
END
$fn$;
@@ -0,0 +1,279 @@
-- Per-tenant schema. The control plane runs this once per tenant with :schema
-- and :role substituted, then runs Fluent's migrations against it.
--
-- The key move: the tenant's role gets a fixed search_path, so the per-tenant
-- worker process never names its own schema. Fluent models declare plain table
-- names ("nodes", "blobs") and resolve into the right schema automatically --
-- the tenant axis is completely invisible to application code.
--
-- ALTER ROLE :role SET search_path = :schema, enclave;
--
-- Tables are owned by enclave_owner, not by the tenant role, so RLS applies
-- normally. FORCE ROW LEVEL SECURITY is set anyway: an ownership change during
-- some future migration would otherwise silently disable every policy.
CREATE SCHEMA :schema;
REVOKE ALL ON SCHEMA :schema FROM PUBLIC;
GRANT USAGE ON SCHEMA :schema TO :role;
GRANT USAGE ON SCHEMA enclave TO :role;
-- ---------------------------------------------------------------- nodes
-- Files and folders in one adjacency-list tree.
CREATE TABLE :schema.nodes (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
parent_id uuid REFERENCES :schema.nodes(id) ON DELETE RESTRICT,
-- Names are ciphertext. name_digest = HMAC(folder_key, normalise(name)),
-- computed client-side: deterministic enough to constrain and index, but
-- keyed per folder so the server can neither invert it nor correlate names
-- across folders.
name_digest bytea NOT NULL,
name_ciphertext bytea NOT NULL,
is_folder boolean NOT NULL,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
blob_id uuid,
size_bytes bigint NOT NULL DEFAULT 0,
created_by uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
-- Polyinstantiation: the same name may exist once per label under a parent, so
-- a low-cleared user creating "Q3 Forecast" never collides with -- and never
-- learns about -- a higher-labeled file of the same name. A plain UNIQUE(name)
-- here would turn the constraint violation into an existence oracle.
CREATE UNIQUE INDEX nodes_polyinstantiated_name
ON :schema.nodes (parent_id, name_digest, classification, compartments)
WHERE deleted_at IS NULL;
-- Every RLS predicate filters on the label pair; keep it leading.
CREATE INDEX nodes_label ON :schema.nodes (classification, compartments);
CREATE INDEX nodes_parent ON :schema.nodes (parent_id) WHERE deleted_at IS NULL;
ALTER TABLE :schema.nodes ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.nodes FORCE ROW LEVEL SECURITY;
CREATE POLICY nodes_read ON :schema.nodes FOR SELECT
USING (enclave.session_dominates(classification, compartments));
-- Strong tranquility: you may only create at exactly your session label.
CREATE POLICY nodes_insert ON :schema.nodes FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
-- USING gates which rows you may touch; WITH CHECK forbids relabelling by
-- UPDATE. Moving a node between labels is a regrade, never a plain write.
CREATE POLICY nodes_update ON :schema.nodes FOR UPDATE
USING (enclave.session_label_is(classification, compartments))
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT, UPDATE ON :schema.nodes TO :role;
-- Tree invariant: a child must dominate its parent, or nobody cleared for the
-- child could traverse to it. The parent lookup runs under the caller's RLS, so
-- an invisible parent is indistinguishable from a missing one -- also correct.
CREATE FUNCTION :schema.enforce_tree_invariant() RETURNS trigger
LANGUAGE plpgsql AS
$$
DECLARE p_class smallint; p_comp bigint;
BEGIN
IF NEW.parent_id IS NULL THEN RETURN NEW; END IF;
SELECT classification, compartments INTO p_class, p_comp
FROM nodes WHERE id = NEW.parent_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'parent not found' USING ERRCODE = 'foreign_key_violation';
END IF;
IF NOT enclave.dominates(NEW.classification, NEW.compartments, p_class, p_comp) THEN
RAISE EXCEPTION 'child label must dominate parent label'
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER nodes_tree_invariant
BEFORE INSERT OR UPDATE OF parent_id, classification, compartments
ON :schema.nodes FOR EACH ROW EXECUTE FUNCTION :schema.enforce_tree_invariant();
-- ---------------------------------------------------------------- blobs
-- Ciphertext blobs. NOT content-addressed, and deliberately not deduplicated.
--
-- Dedup would need convergent encryption (key derived from plaintext), which
-- gives the server a confirmation-of-file oracle: encrypt a candidate, see
-- whether the ciphertext already exists, and learn that some user holds it.
-- That is a leak in any zero-knowledge system, and across labels it is also the
-- covert channel that lets a low-cleared user probe for high-labeled content.
-- Every upload is a distinct blob under a distinct key. Deliberate cost.
CREATE TABLE :schema.blobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
size_bytes bigint NOT NULL,
object_key text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE :schema.blobs ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.blobs FORCE ROW LEVEL SECURITY;
CREATE POLICY blobs_read ON :schema.blobs FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY blobs_insert ON :schema.blobs FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT ON :schema.blobs TO :role;
-- Per-label quota, for the same reason. A single tenant-wide counter would let
-- a low user infer high-label activity from the remaining-space figure.
CREATE TABLE :schema.quotas (
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
limit_bytes bigint NOT NULL,
used_bytes bigint NOT NULL DEFAULT 0,
PRIMARY KEY (classification, compartments)
);
ALTER TABLE :schema.quotas ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.quotas FORCE ROW LEVEL SECURITY;
CREATE POLICY quotas_read ON :schema.quotas FOR SELECT
USING (enclave.session_label_is(classification, compartments));
GRANT SELECT ON :schema.quotas TO :role;
-- ---------------------------------------------------------------- regrade
-- Moving a node down the lattice is the one privileged operation. Two distinct
-- reviewers, an immutable record, and no path that mutates nodes directly.
CREATE TABLE :schema.regrade_requests (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
node_id uuid NOT NULL REFERENCES :schema.nodes(id),
from_class smallint NOT NULL,
from_comp bigint NOT NULL,
to_class smallint NOT NULL,
to_comp bigint NOT NULL,
justification text NOT NULL CHECK (length(justification) >= 20),
requested_by uuid NOT NULL,
reviewer_a uuid,
reviewer_b uuid,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','approved','rejected','applied')),
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (reviewer_a IS DISTINCT FROM reviewer_b),
CHECK (reviewer_a IS DISTINCT FROM requested_by),
CHECK (reviewer_b IS DISTINCT FROM requested_by)
);
ALTER TABLE :schema.regrade_requests ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.regrade_requests FORCE ROW LEVEL SECURITY;
CREATE POLICY regrade_read ON :schema.regrade_requests FOR SELECT
USING (enclave.session_dominates(from_class, from_comp));
GRANT SELECT, INSERT, UPDATE ON :schema.regrade_requests TO :role;
-- ---------------------------------------------------------------- audit
-- Append-only. Audit rows carry the label of what they describe, so the log
-- itself cannot become the leak.
CREATE TABLE :schema.audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor_id uuid NOT NULL,
session_class smallint NOT NULL,
session_comp bigint NOT NULL,
action text NOT NULL,
node_id uuid,
classification smallint NOT NULL,
compartments bigint NOT NULL,
detail jsonb NOT NULL DEFAULT '{}'::jsonb
);
ALTER TABLE :schema.audit_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.audit_log FORCE ROW LEVEL SECURITY;
CREATE POLICY audit_read ON :schema.audit_log FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY audit_insert ON :schema.audit_log FOR INSERT WITH CHECK (true);
-- No UPDATE or DELETE grant, ever. Retention is a partition drop by the owner.
GRANT SELECT, INSERT ON :schema.audit_log TO :role;
-- ---------------------------------------------------------------- keys
-- Label keys, wrapped to each principal whose clearance permits the label.
-- The server stores only wrapped blobs; it holds no key that opens any of them.
CREATE TABLE :schema.label_key_grants (
-- Surrogate key so the ORM can address a row; the tuple below is the real
-- identity and is kept unique.
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
principal_id uuid NOT NULL,
generation integer NOT NULL DEFAULT 1,
wrapped_key bytea NOT NULL,
granted_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (classification, compartments, principal_id, generation)
);
ALTER TABLE :schema.label_key_grants ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.label_key_grants FORCE ROW LEVEL SECURITY;
-- A principal may read only their own grants. Seeing who else is cleared for a
-- compartment is itself sensitive, so this is not a dominance test.
CREATE POLICY label_key_grants_read ON :schema.label_key_grants FOR SELECT
USING (principal_id = NULLIF(current_setting('enclave.principal', true), '')::uuid);
GRANT SELECT, INSERT ON :schema.label_key_grants TO :role;
-- Node keys, wrapped to the node's LABEL key -- never to the parent's node key.
-- The CHECK is the database's copy of KeyHierarchy.validate: it makes the
-- misalignment that would silently undo the lattice unrepresentable.
CREATE TABLE :schema.node_keys (
node_id uuid PRIMARY KEY REFERENCES :schema.nodes(id) ON DELETE CASCADE,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
generation integer NOT NULL DEFAULT 1,
wrapped_key bytea NOT NULL
);
CREATE FUNCTION :schema.enforce_key_label_alignment() RETURNS trigger
LANGUAGE plpgsql AS
$$
DECLARE n_class smallint; n_comp bigint;
BEGIN
SELECT classification, compartments INTO n_class, n_comp
FROM nodes WHERE id = NEW.node_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'node not found' USING ERRCODE = 'foreign_key_violation';
END IF;
IF NEW.classification <> n_class OR NEW.compartments <> n_comp THEN
RAISE EXCEPTION 'node key must be wrapped to its own label key'
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER node_keys_label_alignment
BEFORE INSERT OR UPDATE ON :schema.node_keys
FOR EACH ROW EXECUTE FUNCTION :schema.enforce_key_label_alignment();
ALTER TABLE :schema.node_keys ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.node_keys FORCE ROW LEVEL SECURITY;
CREATE POLICY node_keys_read ON :schema.node_keys FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY node_keys_insert ON :schema.node_keys FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT ON :schema.node_keys TO :role;
-- A downgrade cannot be executed by the server: it must decrypt under the old
-- label key and re-encrypt under the new one, and the server holds neither.
-- So 'approved' is a request awaiting a cleared client to perform the rewrap,
-- and only that client can move it to 'applied'.
ALTER TABLE :schema.regrade_requests
ADD COLUMN applied_by uuid,
ADD COLUMN applied_at timestamptz,
ADD CONSTRAINT regrade_applied_requires_client
CHECK ((status <> 'applied') OR (applied_by IS NOT NULL AND applied_at IS NOT NULL));
+57
View File
@@ -0,0 +1,57 @@
import Fluent
import FluentPostgresDriver
import JWT
import Leaf
import Vapor
import EnclaveAccess
func configure(_ app: Application) async throws {
// MARK: database
//
// A worker connects as its own tenant role, whose search_path points at that
// tenant's schema. The role has USAGE on nothing else, so a bug in this
// process cannot address another tenant's tables -- there is no grant to.
guard let databaseURL = Environment.get("DATABASE_URL") else {
throw Abort(.internalServerError, reason: "DATABASE_URL is required")
}
app.databases.use(.postgres(configuration: try .init(url: databaseURL)), as: .psql)
// MARK: token verification
//
// Clearance arrives in a token minted by the control plane. This secret
// verifies signatures; it never mints anything here.
guard let jwtSecret = Environment.get("ENCLAVE_JWT_SECRET"), jwtSecret.count >= 32 else {
throw Abort(.internalServerError,
reason: "ENCLAVE_JWT_SECRET is required and must be at least 32 characters")
}
await app.jwt.keys.add(hmac: .init(from: jwtSecret), digestAlgorithm: .sha256)
// MARK: views
app.views.use(.leaf)
// MARK: schema
app.migrations.add(InstallSharedSchema())
if let tenant = Environment.get("ENCLAVE_TENANT") {
app.migrations.add(InstallTenantSchema(slug: tenant))
}
// Opt-in, so a self-hoster upgrading a running deployment chooses when DDL
// executes rather than having it happen on restart.
if Environment.get("ENCLAVE_AUTO_MIGRATE") == "true" {
try await app.autoMigrate()
}
// MARK: safety
//
// Skipped for the migrate command, which legitimately runs as the schema
// owner. Serving traffic as that role is what must never happen.
if !CommandLine.arguments.contains("migrate") {
try await RLSGuard.assertRowLevelSecurityApplies(app)
}
// MARK: uploads
// Ciphertext only, but still worth a ceiling.
app.routes.defaultMaxBodySize = "64mb"
try routes(app)
}
+21
View File
@@ -0,0 +1,21 @@
import Vapor
import Logging
@main
enum Entrypoint {
static func main() async throws {
var environment = try Environment.detect()
try LoggingSystem.bootstrap(from: &environment)
let app = try await Application.make(environment)
do {
try await configure(app)
} catch {
app.logger.report(error: error)
try? await app.asyncShutdown()
throw error
}
try await app.execute()
try await app.asyncShutdown()
}
}
+21
View File
@@ -0,0 +1,21 @@
import Fluent
import Vapor
import EnclaveAccess
func routes(_ app: Application) throws {
app.get("healthz") { _ async -> String in "ok" }
// The shell. Everything the file browser displays is decrypted in the
// browser, so Leaf renders the frame and the client fills it in.
app.get { request async throws -> View in
try await request.view.render("shell")
}
// Strong tranquility: writes happen at exactly the session label. See
// WriteRule for why the *-property alternative is not the default.
let session = EnclaveSessionMiddleware(policy: Policy(writeRule: .equal))
let authenticated = app.grouped(session)
try authenticated.register(collection: NodeController())
try authenticated.register(collection: KeyController())
}
@@ -0,0 +1,250 @@
import XCTest
import Foundation
@testable import EnclaveLattice
@testable import EnclaveAccess
@testable import EnclaveCrypto
// Tenant-agnostic fixtures: ordinals and bit positions only.
private let PUBLIC = Classification(0)
private let INTERNAL = Classification(1)
private let CONFIDENTIAL = Classification(2)
private let RESTRICTED = Classification(3)
private let FINANCE = Compartments(bits: [0])
private let LEGAL = Compartments(bits: [1])
private let BOTH = Compartments(bits: [0, 1])
private func L(_ c: Classification, _ k: Compartments = .empty) -> Label {
Label(classification: c, compartments: k)
}
final class LatticeTests: XCTestCase {
// MARK: partial-order laws
func testDominanceIsReflexive() {
for label in [L(PUBLIC), L(CONFIDENTIAL, FINANCE), L(RESTRICTED, BOTH)] {
XCTAssertTrue(label.dominates(label))
}
}
func testDominanceIsAntisymmetric() {
let a = L(CONFIDENTIAL, FINANCE)
let b = L(RESTRICTED, BOTH)
XCTAssertTrue(b.dominates(a))
XCTAssertFalse(a.dominates(b))
}
func testDominanceIsTransitive() {
let low = L(INTERNAL, .empty)
let mid = L(CONFIDENTIAL, FINANCE)
let high = L(RESTRICTED, BOTH)
XCTAssertTrue(mid.dominates(low))
XCTAssertTrue(high.dominates(mid))
XCTAssertTrue(high.dominates(low))
}
/// The case that a total-order model gets wrong: higher classification does
/// not imply dominance when compartments diverge.
func testHigherClassificationDoesNotImplyDominance() {
let secretFinance = L(CONFIDENTIAL, FINANCE)
let restrictedLegal = L(RESTRICTED, LEGAL)
XCTAssertFalse(restrictedLegal.dominates(secretFinance))
XCTAssertFalse(secretFinance.dominates(restrictedLegal))
XCTAssertTrue(secretFinance.isIncomparable(to: restrictedLegal))
}
func testLeastUpperBoundAbsorbsBothInputs() {
let lub = Label.leastUpperBound(L(CONFIDENTIAL, FINANCE), L(RESTRICTED, LEGAL))
XCTAssertEqual(lub, L(RESTRICTED, BOTH))
XCTAssertTrue(lub.dominates(L(CONFIDENTIAL, FINANCE)))
XCTAssertTrue(lub.dominates(L(RESTRICTED, LEGAL)))
}
func testGreatestLowerBoundIsDominatedByBothInputs() {
let glb = Label.greatestLowerBound(L(CONFIDENTIAL, BOTH), L(RESTRICTED, LEGAL))
XCTAssertEqual(glb, L(CONFIDENTIAL, LEGAL))
XCTAssertTrue(L(CONFIDENTIAL, BOTH).dominates(glb))
XCTAssertTrue(L(RESTRICTED, LEGAL).dominates(glb))
}
// MARK: clearance
func testClearanceRejectsLabelIncomparableToMaximum() {
let clearance = Clearance(maximum: L(RESTRICTED, FINANCE))
XCTAssertTrue(clearance.permits(L(CONFIDENTIAL, FINANCE)))
// Cleared to RESTRICTED, but never read into LEGAL.
XCTAssertFalse(clearance.permits(L(INTERNAL, LEGAL)))
}
// MARK: compartment encoding
func testCompartmentsRoundTripAsBitPositions() throws {
let original = Compartments(bits: [0, 7, 63])
let data = try JSONEncoder().encode(original)
XCTAssertEqual(String(data: data, encoding: .utf8), "[0,7,63]")
XCTAssertEqual(try JSONDecoder().decode(Compartments.self, from: data), original)
}
}
final class PolicyTests: XCTestCase {
private let policy = Policy(writeRule: .equal)
/// The core inference-control requirement: failing to dominate an object is
/// reported as absence, never as refusal.
func testUndominatedReadIsReportedAsNotFound() {
let decision = policy.decide(
subject: L(INTERNAL),
object: L(RESTRICTED, FINANCE),
mode: .read
)
XCTAssertEqual(decision, .denyNotVisible)
XCTAssertEqual(decision.httpStatus, 404)
}
func testVisibleButLowerObjectIsReadOnly() {
let decision = policy.decide(
subject: L(RESTRICTED, BOTH),
object: L(INTERNAL),
mode: .write
)
XCTAssertEqual(decision, .denyReadOnly)
XCTAssertEqual(decision.httpStatus, 403)
}
func testWriteAtSessionLabelIsAllowed() {
let label = L(CONFIDENTIAL, FINANCE)
XCTAssertEqual(policy.decide(subject: label, object: label, mode: .write), .allow)
}
func testSessionOutsideClearanceIsRejected() {
let clearance = Clearance(maximum: L(CONFIDENTIAL, FINANCE))
XCTAssertEqual(policy.session(at: L(RESTRICTED, FINANCE), for: clearance), .denyOutsideClearance)
}
}
final class TreeTests: XCTestCase {
func testChildMustDominateParent() {
XCTAssertNoThrow(try Tree.validate(child: L(RESTRICTED, FINANCE), parent: L(INTERNAL)))
XCTAssertThrowsError(try Tree.validate(child: L(INTERNAL), parent: L(RESTRICTED, FINANCE)))
}
/// Creating at the session label can never break the tree invariant, because
/// traversal into the parent already required dominating it.
func testNewNodeLabelPreservesInvariant() throws {
let parent = L(INTERNAL)
let session = L(CONFIDENTIAL, FINANCE)
let assigned = Tree.labelForNewNode(session: session, parent: parent)
XCTAssertEqual(assigned, session)
XCTAssertNoThrow(try Tree.validate(child: assigned, parent: parent))
}
func testPolyinstantiatedNamesResolvePerSession() {
let lowID = UUID(), highID = UUID()
let children = [
Node(id: lowID, parentID: nil, name: NameDigest(plaintext: "Q3 Forecast"), label: L(INTERNAL), isFolder: false),
Node(id: highID, parentID: nil, name: NameDigest(plaintext: "Q3 Forecast"), label: L(RESTRICTED, FINANCE), isFolder: false),
]
// The low session sees exactly one file, and does not learn of the other.
XCTAssertEqual(Tree.visibleChildren(of: children, at: L(INTERNAL)).count, 1)
XCTAssertEqual(Tree.resolve(name: NameDigest(plaintext: "Q3 Forecast"), among: children, at: L(INTERNAL)), .found(lowID))
// The cleared session sees both, and its exact-label instance wins.
XCTAssertEqual(Tree.visibleChildren(of: children, at: L(RESTRICTED, FINANCE)).count, 2)
XCTAssertEqual(
Tree.resolve(name: NameDigest(plaintext: "Q3 Forecast"), among: children, at: L(RESTRICTED, FINANCE)),
.found(highID)
)
}
func testMissingAndHiddenNamesAreIndistinguishable() {
let hidden = [Node(id: UUID(), parentID: nil, name: NameDigest(plaintext: "Payroll"), label: L(RESTRICTED, FINANCE), isFolder: false)]
XCTAssertEqual(Tree.resolve(name: NameDigest(plaintext: "Payroll"), among: hidden, at: L(INTERNAL)), .notVisible)
XCTAssertEqual(Tree.resolve(name: NameDigest(plaintext: "No Such File"), among: hidden, at: L(INTERNAL)), .notVisible)
}
func testIncomparableSiblingsWithSameNameAreAmbiguous() {
let a = UUID(), b = UUID()
let children = [
Node(id: a, parentID: nil, name: NameDigest(plaintext: "Notes"), label: L(CONFIDENTIAL, FINANCE), isFolder: false),
Node(id: b, parentID: nil, name: NameDigest(plaintext: "Notes"), label: L(CONFIDENTIAL, LEGAL), isFolder: false),
]
guard case .ambiguous(let ids) = Tree.resolve(name: NameDigest(plaintext: "Notes"), among: children, at: L(RESTRICTED, BOTH)) else {
return XCTFail("expected ambiguity between incomparable instances")
}
XCTAssertEqual(Set(ids), Set([a, b]))
}
}
final class PostgresEncodingTests: XCTestCase {
/// The bit-63 case: a naive UInt64 -> Int64 conversion traps here.
func testHighBitSurvivesSignedRoundTrip() {
let all = Compartments(bits: Array(0...63))
XCTAssertEqual(all.postgresBitPattern, -1)
XCTAssertEqual(Compartments(postgresBitPattern: all.postgresBitPattern), all)
}
/// Dominance must agree across the language boundary for negative masks.
func testDominanceHoldsUnderSignedRepresentation() {
let subject = Compartments(bits: Array(0...63))
let object = Compartments(bits: [63])
XCTAssertTrue(subject.isSuperset(of: object))
XCTAssertEqual(subject.postgresBitPattern & object.postgresBitPattern,
object.postgresBitPattern)
}
}
final class KeyHierarchyTests: XCTestCase {
private let node = UUID()
private let principal = UUID()
private func key(_ ref: KeyRef) -> WrappedKey {
WrappedKey(ciphertext: Data([0xAB]), wrappedTo: ref)
}
func testNodeKeyWrappedToItsOwnLabelIsAccepted() {
let label = L(CONFIDENTIAL, FINANCE)
XCTAssertNoThrow(try KeyHierarchy.validate(nodeID: node, nodeLabel: label, key: key(.label(label))))
}
/// The mistake this module exists to catch: deriving a node key from its
/// parent folder's key. The tree invariant allows a RESTRICTED file inside a
/// CONFIDENTIAL folder, so parent-wrapping would hand the folder key holder
/// content above their clearance regardless of what RLS serves.
func testNodeKeyWrappedToParentFolderIsRejected() {
let parentNode = UUID()
XCTAssertThrowsError(
try KeyHierarchy.validate(
nodeID: node,
nodeLabel: L(RESTRICTED, FINANCE),
key: key(.node(parentNode))
)
) { error in
guard case KeyHierarchyError.nodeKeyNotWrappedToItsLabel = error else {
return XCTFail("expected label-misalignment error, got \(error)")
}
}
}
func testNodeKeyWrappedToADifferentLabelIsRejected() {
XCTAssertThrowsError(
try KeyHierarchy.validate(
nodeID: node,
nodeLabel: L(RESTRICTED, FINANCE),
key: key(.label(L(CONFIDENTIAL, FINANCE)))
)
)
}
func testGrantBeyondClearanceIsRejected() {
let grant = LabelKeyGrant(
label: L(RESTRICTED, BOTH),
principalID: principal,
wrapped: key(.identity(principalID: principal)),
generation: 1
)
let clearance = Clearance(maximum: L(RESTRICTED, FINANCE))
XCTAssertThrowsError(try KeyHierarchy.validate(grant: grant, clearance: clearance))
}
}
+70
View File
@@ -0,0 +1,70 @@
# Self-hosting Enclave.
#
# Note the two roles. `migrate` connects as the schema owner because installing
# policies, triggers and grants requires it. `app` connects as the per-tenant
# role, which is neither a superuser nor BYPASSRLS -- if it were, every
# row-level security policy would be silently ignored and no label would be
# enforced. The server checks this at boot and refuses to start rather than
# serve unlabelled data. See SELF-HOSTING.md.
services:
db:
image: postgres:18-alpine
environment:
POSTGRES_DB: enclave
POSTGRES_USER: enclave_owner
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
volumes:
# Postgres 18 expects a single mount at /var/lib/postgresql, NOT at
# /var/lib/postgresql/data as in 17 and earlier -- data then lives in a
# version-named subdirectory so `pg_upgrade --link` works across a mount
# boundary. Using the old path makes the container restart-loop on boot.
#
# Named explicitly: an anonymous volume shows up as "dangling" and gets
# destroyed by a routine `docker volume prune`. This one holds every file
# your users have.
- enclave-pgdata:/var/lib/postgresql
healthcheck:
test: ["CMD-SHELL", "pg_isready -U enclave_owner -d enclave"]
interval: 5s
timeout: 5s
retries: 12
restart: unless-stopped
# Deliberately not published to the host. Reach it with `docker compose exec db psql`.
migrate:
build: .
depends_on:
db:
condition: service_healthy
environment:
DATABASE_URL: postgres://enclave_owner:${POSTGRES_PASSWORD}@db:5432/enclave
ENCLAVE_JWT_SECRET: ${ENCLAVE_JWT_SECRET:?set ENCLAVE_JWT_SECRET in .env}
ENCLAVE_TENANT: ${ENCLAVE_TENANT:-default}
ENCLAVE_TENANT_PASSWORD: ${ENCLAVE_TENANT_PASSWORD:?set ENCLAVE_TENANT_PASSWORD in .env}
command: ["migrate", "--yes"]
restart: "no"
app:
build: .
depends_on:
migrate:
condition: service_completed_successfully
environment:
# The tenant role, not the owner. This is the whole point.
DATABASE_URL: postgres://tenant_${ENCLAVE_TENANT:-default}:${ENCLAVE_TENANT_PASSWORD}@db:5432/enclave
ENCLAVE_JWT_SECRET: ${ENCLAVE_JWT_SECRET}
ENCLAVE_TENANT: ${ENCLAVE_TENANT:-default}
LOG_LEVEL: ${LOG_LEVEL:-info}
ports:
- "${ENCLAVE_BIND:-127.0.0.1}:8080:8080"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 15s
timeout: 5s
retries: 5
restart: unless-stopped
volumes:
enclave-pgdata:
name: enclave-pgdata
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
#
# Every database access must go through `req.labeled { }`, which pins the
# session label into the transaction that RLS reads. A handler that reaches for
# `req.db` directly runs without a label -- which fails closed, returning an
# empty result set rather than an error, and is therefore easy to ship.
#
# Run in CI.
set -euo pipefail
cd "$(dirname "$0")/.."
matches="$(grep -rn --include='*.swift' -E '\breq(uest)?\.db\b' Sources/EnclaveServer \
| grep -v 'Database/LabeledDatabase.swift' || true)"
if [ -n "$matches" ]; then
echo "error: direct database access outside req.labeled { }:" >&2
echo "$matches" >&2
echo >&2
echo "Use 'try await request.labeled { db in ... }' instead." >&2
exit 1
fi
echo "ok: all database access goes through req.labeled"
+103
View File
@@ -0,0 +1,103 @@
-- Shared objects. Installed once per database, owned by enclave_owner.
-- Tenant workers get EXECUTE on the helpers and nothing else here.
CREATE SCHEMA IF NOT EXISTS enclave;
CREATE SCHEMA IF NOT EXISTS enclave_control;
-- Session label, read from transaction-local GUCs.
--
-- The `true` second argument makes a missing setting return NULL rather than
-- raise. NULL then makes every dominance test NULL, which RLS treats as false:
-- a worker that forgets to set its session label sees zero rows. Fail-closed by
-- construction, but it does mean "empty result set" is the symptom of a wiring
-- bug -- the Vapor middleware asserts the GUCs are present for that reason.
CREATE OR REPLACE FUNCTION enclave.session_classification() RETURNS smallint
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('enclave.classification', true), '')::smallint $$;
CREATE OR REPLACE FUNCTION enclave.session_compartments() RETURNS bigint
LANGUAGE sql STABLE AS
$$ SELECT NULLIF(current_setting('enclave.compartments', true), '')::bigint $$;
-- A ⊒ B: at least as high on the ladder AND a superset of compartments.
-- Compartments are a signed bigint here; bit 63 makes the value negative, which
-- is harmless because `&` is a pure bit operation. The Swift side must convert
-- with Int64(bitPattern:) rather than a checked cast.
CREATE OR REPLACE FUNCTION enclave.dominates(
subject_class smallint, subject_comp bigint,
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql IMMUTABLE PARALLEL SAFE AS
$$ SELECT subject_class >= object_class AND (subject_comp & object_comp) = object_comp $$;
-- Convenience wrapper used by every read policy.
CREATE OR REPLACE FUNCTION enclave.session_dominates(
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql STABLE AS
$$ SELECT enclave.dominates(
enclave.session_classification(), enclave.session_compartments(),
object_class, object_comp) $$;
CREATE OR REPLACE FUNCTION enclave.session_label_is(
object_class smallint, object_comp bigint
) RETURNS boolean LANGUAGE sql STABLE AS
$$ SELECT enclave.session_classification() = object_class
AND enclave.session_compartments() = object_comp $$;
-- Control plane. Lives outside every tenant schema; tenant roles cannot read it.
CREATE TABLE IF NOT EXISTS enclave_control.tenants (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
slug text UNIQUE NOT NULL CHECK (slug ~ '^[a-z][a-z0-9-]{1,38}$'),
schema_name text UNIQUE NOT NULL,
db_role text UNIQUE NOT NULL,
status text NOT NULL DEFAULT 'provisioning',
created_at timestamptz NOT NULL DEFAULT now()
);
-- Tenants name their own ladder; the lattice code only sees ordinals.
CREATE TABLE IF NOT EXISTS enclave_control.classification_levels (
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
ordinal smallint NOT NULL CHECK (ordinal >= 0),
name text NOT NULL,
PRIMARY KEY (tenant_id, ordinal),
UNIQUE (tenant_id, name)
);
CREATE TABLE IF NOT EXISTS enclave_control.compartments (
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
bit smallint NOT NULL CHECK (bit BETWEEN 0 AND 63),
name text NOT NULL,
PRIMARY KEY (tenant_id, bit),
UNIQUE (tenant_id, name)
);
CREATE TABLE IF NOT EXISTS enclave_control.principals (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id uuid NOT NULL REFERENCES enclave_control.tenants(id) ON DELETE CASCADE,
email text NOT NULL,
max_class smallint NOT NULL,
max_comp bigint NOT NULL DEFAULT 0,
min_class smallint NOT NULL DEFAULT 0,
min_comp bigint NOT NULL DEFAULT 0,
UNIQUE (tenant_id, email)
);
-- Role management. DDL cannot take bind parameters, so these wrap format()'s
-- %I/%L quoting -- the identifier and the password are escaped by Postgres
-- rather than by string-building in the application.
CREATE OR REPLACE FUNCTION enclave.ensure_role(role_name text) RETURNS void
LANGUAGE plpgsql AS
$fn$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = role_name) THEN
EXECUTE format('CREATE ROLE %I NOLOGIN', role_name);
END IF;
END
$fn$;
CREATE OR REPLACE FUNCTION enclave.set_role_login(role_name text, role_password text)
RETURNS void LANGUAGE plpgsql AS
$fn$
BEGIN
EXECUTE format('ALTER ROLE %I LOGIN PASSWORD %L', role_name, role_password);
END
$fn$;
+279
View File
@@ -0,0 +1,279 @@
-- Per-tenant schema. The control plane runs this once per tenant with :schema
-- and :role substituted, then runs Fluent's migrations against it.
--
-- The key move: the tenant's role gets a fixed search_path, so the per-tenant
-- worker process never names its own schema. Fluent models declare plain table
-- names ("nodes", "blobs") and resolve into the right schema automatically --
-- the tenant axis is completely invisible to application code.
--
-- ALTER ROLE :role SET search_path = :schema, enclave;
--
-- Tables are owned by enclave_owner, not by the tenant role, so RLS applies
-- normally. FORCE ROW LEVEL SECURITY is set anyway: an ownership change during
-- some future migration would otherwise silently disable every policy.
CREATE SCHEMA :schema;
REVOKE ALL ON SCHEMA :schema FROM PUBLIC;
GRANT USAGE ON SCHEMA :schema TO :role;
GRANT USAGE ON SCHEMA enclave TO :role;
-- ---------------------------------------------------------------- nodes
-- Files and folders in one adjacency-list tree.
CREATE TABLE :schema.nodes (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
parent_id uuid REFERENCES :schema.nodes(id) ON DELETE RESTRICT,
-- Names are ciphertext. name_digest = HMAC(folder_key, normalise(name)),
-- computed client-side: deterministic enough to constrain and index, but
-- keyed per folder so the server can neither invert it nor correlate names
-- across folders.
name_digest bytea NOT NULL,
name_ciphertext bytea NOT NULL,
is_folder boolean NOT NULL,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
blob_id uuid,
size_bytes bigint NOT NULL DEFAULT 0,
created_by uuid NOT NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
deleted_at timestamptz
);
-- Polyinstantiation: the same name may exist once per label under a parent, so
-- a low-cleared user creating "Q3 Forecast" never collides with -- and never
-- learns about -- a higher-labeled file of the same name. A plain UNIQUE(name)
-- here would turn the constraint violation into an existence oracle.
CREATE UNIQUE INDEX nodes_polyinstantiated_name
ON :schema.nodes (parent_id, name_digest, classification, compartments)
WHERE deleted_at IS NULL;
-- Every RLS predicate filters on the label pair; keep it leading.
CREATE INDEX nodes_label ON :schema.nodes (classification, compartments);
CREATE INDEX nodes_parent ON :schema.nodes (parent_id) WHERE deleted_at IS NULL;
ALTER TABLE :schema.nodes ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.nodes FORCE ROW LEVEL SECURITY;
CREATE POLICY nodes_read ON :schema.nodes FOR SELECT
USING (enclave.session_dominates(classification, compartments));
-- Strong tranquility: you may only create at exactly your session label.
CREATE POLICY nodes_insert ON :schema.nodes FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
-- USING gates which rows you may touch; WITH CHECK forbids relabelling by
-- UPDATE. Moving a node between labels is a regrade, never a plain write.
CREATE POLICY nodes_update ON :schema.nodes FOR UPDATE
USING (enclave.session_label_is(classification, compartments))
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT, UPDATE ON :schema.nodes TO :role;
-- Tree invariant: a child must dominate its parent, or nobody cleared for the
-- child could traverse to it. The parent lookup runs under the caller's RLS, so
-- an invisible parent is indistinguishable from a missing one -- also correct.
CREATE FUNCTION :schema.enforce_tree_invariant() RETURNS trigger
LANGUAGE plpgsql AS
$$
DECLARE p_class smallint; p_comp bigint;
BEGIN
IF NEW.parent_id IS NULL THEN RETURN NEW; END IF;
SELECT classification, compartments INTO p_class, p_comp
FROM nodes WHERE id = NEW.parent_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'parent not found' USING ERRCODE = 'foreign_key_violation';
END IF;
IF NOT enclave.dominates(NEW.classification, NEW.compartments, p_class, p_comp) THEN
RAISE EXCEPTION 'child label must dominate parent label'
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER nodes_tree_invariant
BEFORE INSERT OR UPDATE OF parent_id, classification, compartments
ON :schema.nodes FOR EACH ROW EXECUTE FUNCTION :schema.enforce_tree_invariant();
-- ---------------------------------------------------------------- blobs
-- Ciphertext blobs. NOT content-addressed, and deliberately not deduplicated.
--
-- Dedup would need convergent encryption (key derived from plaintext), which
-- gives the server a confirmation-of-file oracle: encrypt a candidate, see
-- whether the ciphertext already exists, and learn that some user holds it.
-- That is a leak in any zero-knowledge system, and across labels it is also the
-- covert channel that lets a low-cleared user probe for high-labeled content.
-- Every upload is a distinct blob under a distinct key. Deliberate cost.
CREATE TABLE :schema.blobs (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
size_bytes bigint NOT NULL,
object_key text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE :schema.blobs ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.blobs FORCE ROW LEVEL SECURITY;
CREATE POLICY blobs_read ON :schema.blobs FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY blobs_insert ON :schema.blobs FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT ON :schema.blobs TO :role;
-- Per-label quota, for the same reason. A single tenant-wide counter would let
-- a low user infer high-label activity from the remaining-space figure.
CREATE TABLE :schema.quotas (
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
limit_bytes bigint NOT NULL,
used_bytes bigint NOT NULL DEFAULT 0,
PRIMARY KEY (classification, compartments)
);
ALTER TABLE :schema.quotas ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.quotas FORCE ROW LEVEL SECURITY;
CREATE POLICY quotas_read ON :schema.quotas FOR SELECT
USING (enclave.session_label_is(classification, compartments));
GRANT SELECT ON :schema.quotas TO :role;
-- ---------------------------------------------------------------- regrade
-- Moving a node down the lattice is the one privileged operation. Two distinct
-- reviewers, an immutable record, and no path that mutates nodes directly.
CREATE TABLE :schema.regrade_requests (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
node_id uuid NOT NULL REFERENCES :schema.nodes(id),
from_class smallint NOT NULL,
from_comp bigint NOT NULL,
to_class smallint NOT NULL,
to_comp bigint NOT NULL,
justification text NOT NULL CHECK (length(justification) >= 20),
requested_by uuid NOT NULL,
reviewer_a uuid,
reviewer_b uuid,
status text NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','approved','rejected','applied')),
created_at timestamptz NOT NULL DEFAULT now(),
CHECK (reviewer_a IS DISTINCT FROM reviewer_b),
CHECK (reviewer_a IS DISTINCT FROM requested_by),
CHECK (reviewer_b IS DISTINCT FROM requested_by)
);
ALTER TABLE :schema.regrade_requests ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.regrade_requests FORCE ROW LEVEL SECURITY;
CREATE POLICY regrade_read ON :schema.regrade_requests FOR SELECT
USING (enclave.session_dominates(from_class, from_comp));
GRANT SELECT, INSERT, UPDATE ON :schema.regrade_requests TO :role;
-- ---------------------------------------------------------------- audit
-- Append-only. Audit rows carry the label of what they describe, so the log
-- itself cannot become the leak.
CREATE TABLE :schema.audit_log (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
occurred_at timestamptz NOT NULL DEFAULT now(),
actor_id uuid NOT NULL,
session_class smallint NOT NULL,
session_comp bigint NOT NULL,
action text NOT NULL,
node_id uuid,
classification smallint NOT NULL,
compartments bigint NOT NULL,
detail jsonb NOT NULL DEFAULT '{}'::jsonb
);
ALTER TABLE :schema.audit_log ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.audit_log FORCE ROW LEVEL SECURITY;
CREATE POLICY audit_read ON :schema.audit_log FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY audit_insert ON :schema.audit_log FOR INSERT WITH CHECK (true);
-- No UPDATE or DELETE grant, ever. Retention is a partition drop by the owner.
GRANT SELECT, INSERT ON :schema.audit_log TO :role;
-- ---------------------------------------------------------------- keys
-- Label keys, wrapped to each principal whose clearance permits the label.
-- The server stores only wrapped blobs; it holds no key that opens any of them.
CREATE TABLE :schema.label_key_grants (
-- Surrogate key so the ORM can address a row; the tuple below is the real
-- identity and is kept unique.
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
principal_id uuid NOT NULL,
generation integer NOT NULL DEFAULT 1,
wrapped_key bytea NOT NULL,
granted_at timestamptz NOT NULL DEFAULT now(),
UNIQUE (classification, compartments, principal_id, generation)
);
ALTER TABLE :schema.label_key_grants ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.label_key_grants FORCE ROW LEVEL SECURITY;
-- A principal may read only their own grants. Seeing who else is cleared for a
-- compartment is itself sensitive, so this is not a dominance test.
CREATE POLICY label_key_grants_read ON :schema.label_key_grants FOR SELECT
USING (principal_id = NULLIF(current_setting('enclave.principal', true), '')::uuid);
GRANT SELECT, INSERT ON :schema.label_key_grants TO :role;
-- Node keys, wrapped to the node's LABEL key -- never to the parent's node key.
-- The CHECK is the database's copy of KeyHierarchy.validate: it makes the
-- misalignment that would silently undo the lattice unrepresentable.
CREATE TABLE :schema.node_keys (
node_id uuid PRIMARY KEY REFERENCES :schema.nodes(id) ON DELETE CASCADE,
classification smallint NOT NULL,
compartments bigint NOT NULL DEFAULT 0,
generation integer NOT NULL DEFAULT 1,
wrapped_key bytea NOT NULL
);
CREATE FUNCTION :schema.enforce_key_label_alignment() RETURNS trigger
LANGUAGE plpgsql AS
$$
DECLARE n_class smallint; n_comp bigint;
BEGIN
SELECT classification, compartments INTO n_class, n_comp
FROM nodes WHERE id = NEW.node_id;
IF NOT FOUND THEN
RAISE EXCEPTION 'node not found' USING ERRCODE = 'foreign_key_violation';
END IF;
IF NEW.classification <> n_class OR NEW.compartments <> n_comp THEN
RAISE EXCEPTION 'node key must be wrapped to its own label key'
USING ERRCODE = 'check_violation';
END IF;
RETURN NEW;
END;
$$;
CREATE TRIGGER node_keys_label_alignment
BEFORE INSERT OR UPDATE ON :schema.node_keys
FOR EACH ROW EXECUTE FUNCTION :schema.enforce_key_label_alignment();
ALTER TABLE :schema.node_keys ENABLE ROW LEVEL SECURITY;
ALTER TABLE :schema.node_keys FORCE ROW LEVEL SECURITY;
CREATE POLICY node_keys_read ON :schema.node_keys FOR SELECT
USING (enclave.session_dominates(classification, compartments));
CREATE POLICY node_keys_insert ON :schema.node_keys FOR INSERT
WITH CHECK (enclave.session_label_is(classification, compartments));
GRANT SELECT, INSERT ON :schema.node_keys TO :role;
-- A downgrade cannot be executed by the server: it must decrypt under the old
-- label key and re-encrypt under the new one, and the server holds neither.
-- So 'approved' is a request awaiting a cleared client to perform the rewrap,
-- and only that client can move it to 'applied'.
ALTER TABLE :schema.regrade_requests
ADD COLUMN applied_by uuid,
ADD COLUMN applied_at timestamptz,
ADD CONSTRAINT regrade_applied_requires_client
CHECK ((status <> 'applied') OR (applied_by IS NOT NULL AND applied_at IS NOT NULL));