Add the shared FlameNet account service

Its own binary, container and database role, granted nothing outside
enclave_accounts. It cannot read a file row and a tenant role cannot read an
account; the signed token is the entire interface between them.

One passphrase yields two unrelated secrets: an authentication secret under
flamenet/<product>/auth/v1 that reaches the service, and an encryption key
under flamenet/<product>/identity/v1 that never leaves the browser. A fully
compromised account service can impersonate a user to itself and decrypt
nothing.

Each product server sees only HMAC(service_secret, account_id || product), so
Files cannot correlate its users with Messenger's. Unknown handles return a
deterministic fake stretch salt, so the endpoint cannot enumerate accounts. No
email is stored. Clearance is granted by CLI, never by an endpoint.

The recovery code now covers both halves — restoring file access while leaving
the account credential stale would have locked the user out either way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Paul Hitt
2026-08-21 13:13:18 -04:00
co-authored by Claude Opus 5
parent 974ab07d53
commit cf6f502348
24 changed files with 1097 additions and 103 deletions
+2 -1
View File
@@ -2,5 +2,6 @@
.git/
.env
*.xcodeproj
Tests/
blobs/
docs/
Public/js/crypto/
+13 -1
View File
@@ -9,10 +9,18 @@ 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.
# Signs and verifies clearance tokens. The account service signs with it, the
# file server verifies with it, and they must match. Minimum 32 chars.
# Rotating this invalidates every outstanding session.
ENCLAVE_JWT_SECRET=
# Derives product-scoped pseudonyms in the account service. Minimum 32 chars.
# Rotating this changes every pseudonym and orphans existing file data.
ENCLAVE_ACCOUNTS_SECRET=
# Password for the account service's own database role.
ENCLAVE_ACCOUNTS_DB_PASSWORD=
# Tenant slug: lowercase letters, digits, underscore; 2-39 chars.
# Becomes schema "t_<slug>" and role "tenant_<slug>".
ENCLAVE_TENANT=default
@@ -21,4 +29,8 @@ ENCLAVE_TENANT=default
# terminating reverse proxy in front; 0.0.0.0 exposes the app directly.
ENCLAVE_BIND=127.0.0.1
# Published host ports. Change these if something already holds 8080/8100.
ENCLAVE_PORT=8080
ENCLAVE_ACCOUNTS_PORT=8100
LOG_LEVEL=info
+19
View File
@@ -97,6 +97,25 @@ 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.
## The account service
A third boundary, orthogonal to the two above. `EnclaveAccounts` runs as its own
process with a role granted `USAGE` on `enclave_accounts` and nothing else — no
tenant schema, no `enclave_control`. The file server's role has no grant on
`enclave_accounts` in return. Neither can read the other's tables, and the
signed token is the whole interface.
One passphrase produces two unrelated secrets: an authentication secret under
`flamenet/<product>/auth/v1`, sent to the account service, and an encryption key
under `flamenet/<product>/identity/v1`, which never leaves the browser. A fully
compromised account service can therefore impersonate a user to itself and
decrypt nothing.
Each product server sees only `HMAC(service_secret, account_id || product)`, so
Files cannot correlate its users with Messenger's. The account service can,
which is precisely why it stores an opaque id, a login handle, a verifier, and
nothing else.
## Labeled-tree rules
Two invariants, enforced in `Tree.swift` and again as database constraints:
+7 -4
View File
@@ -19,11 +19,14 @@ COPY scripts ./scripts
RUN ./scripts/build-web.sh
# Static stdlib keeps the runtime image free of a Swift installation.
RUN swift build -c release --product EnclaveServer --static-swift-stdlib
# One image, both products: they share the token target and are deployed as
# separate containers from the same build.
RUN swift build -c release --product EnclaveServer --static-swift-stdlib \
&& swift build -c release --product EnclaveAccounts --static-swift-stdlib
WORKDIR /staging
RUN BIN="$(swift build --package-path /build -c release --show-bin-path)" \
&& cp "$BIN/EnclaveServer" ./ \
&& cp "$BIN/EnclaveServer" "$BIN/EnclaveAccounts" ./ \
&& find -L "$BIN" -regex '.*\.resources$' -exec cp -Ra {} ./ \; \
&& cp -r /build/Resources ./Resources \
&& cp -r /build/Public ./Public
@@ -44,5 +47,5 @@ RUN mkdir -p /app/blobs && chown enclave:enclave /app/blobs
USER enclave:enclave
EXPOSE 8080
ENTRYPOINT ["./EnclaveServer"]
CMD ["serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"]
# No ENTRYPOINT: compose selects which binary this container runs.
CMD ["./EnclaveServer", "serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8080"]
+26 -1
View File
@@ -9,6 +9,7 @@ let package = Package(
.library(name: "EnclaveAccess", targets: ["EnclaveAccess"]),
.library(name: "EnclaveCrypto", targets: ["EnclaveCrypto"]),
.executable(name: "EnclaveServer", targets: ["EnclaveServer"]),
.executable(name: "EnclaveAccounts", targets: ["EnclaveAccounts"]),
],
dependencies: [
.package(url: "https://github.com/vapor/vapor.git", from: "4.106.0"),
@@ -23,10 +24,34 @@ let package = Package(
.target(name: "EnclaveCrypto", dependencies: ["EnclaveLattice"]),
.target(name: "EnclaveAccess", dependencies: ["EnclaveLattice", "EnclaveCrypto"]),
// Shared by the account service and the file server: the token is the
// only thing that crosses between them.
.target(
name: "EnclaveAuth",
dependencies: [
"EnclaveLattice",
.product(name: "Vapor", package: "vapor"),
.product(name: "JWT", package: "jwt"),
]
),
.executableTarget(
name: "EnclaveAccounts",
dependencies: [
"EnclaveLattice", "EnclaveAuth",
.product(name: "Vapor", package: "vapor"),
.product(name: "Fluent", package: "fluent"),
.product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"),
.product(name: "JWT", package: "jwt"),
],
resources: [.copy("SQL")],
swiftSettings: [.swiftLanguageMode(.v5)]
),
.executableTarget(
name: "EnclaveServer",
dependencies: [
"EnclaveLattice", "EnclaveAccess", "EnclaveCrypto",
"EnclaveLattice", "EnclaveAccess", "EnclaveCrypto", "EnclaveAuth",
.product(name: "Vapor", package: "vapor"),
.product(name: "Fluent", package: "fluent"),
.product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"),
+63 -21
View File
@@ -1,4 +1,6 @@
import { EnclaveAPI } from "./crypto/api.js";
import { AccountsAPI } from "./crypto/accounts.js";
import { generateRecoveryCode, decode as decodeRecoveryCode } from "./crypto/recovery.js";
import { Session } from "./crypto/session.js";
import { label as makeLabel, permits } from "./crypto/lattice.js";
import { utf8, fromUtf8 } from "./crypto/bytes.js";
@@ -156,42 +158,81 @@ async function download(row) {
// ---------------------------------------------------------------- actions
let recoveryMode = false;
const accounts = new AccountsAPI(
document.querySelector('meta[name="enclave-accounts"]')?.content ?? ""
);
function setRecoveryMode(on) {
recoveryMode = on;
show($("passphrase-field"), !on);
show($("recovery-field"), on);
show($("new-passphrase-field"), on);
$("mode-toggle").textContent = on ? "Back to signing in" : "I've lost my passphrase";
$("signin-button").textContent = on ? "Recover access" : "Unlock";
// "signin" | "register" | "recover"
let mode = "signin";
function setMode(next) {
mode = next;
const recovering = next === "recover";
show($("passphrase-field"), !recovering);
show($("recovery-field"), recovering);
show($("new-passphrase-field"), recovering);
$("mode-toggle").textContent = recovering ? "Back to signing in" : "I've lost my passphrase";
$("register-toggle").textContent = next === "register" ? "Back to signing in" : "Create an account";
show($("register-toggle"), !recovering);
$("signin-button").textContent =
recovering ? "Recover access" : next === "register" ? "Create account" : "Unlock";
}
async function signIn() {
const token = $("token").value.trim();
if (!token) return status("a clearance token is required", "error");
try {
clearance = readClearance(token);
} catch {
return status("that token could not be read", "error");
}
const api = new EnclaveAPI({ token });
const handle = $("handle").value.trim();
if (!handle) return status("a handle is required", "error");
// Key derivation is deliberately slow, so say so rather than looking hung.
status("deriving keys on this device… (slow on purpose)");
let token, freshEntropy = null, recoverEntropy = null, nextEntropy = null;
try {
if (recoveryMode) {
if (mode === "register") {
const passphrase = $("passphrase").value;
if (!passphrase) return status("a passphrase is required", "error");
// One code, generated here and bound to both halves: the account
// credential and the file key. Recovering one without the other
// would leave you locked out either way.
freshEntropy = (await generateRecoveryCode()).entropy;
await accounts.register({ handle, passphrase, recoveryEntropy: freshEntropy });
({ token } = await accounts.signIn({ handle, passphrase }));
} else if (mode === "recover") {
const code = $("recovery-code").value.trim();
const newPassphrase = $("new-passphrase").value;
if (!code || !newPassphrase) {
return status("recovery code and a new passphrase are both required", "error");
}
session = await Session.recover({ api, code, newPassphrase, clearance });
recoverEntropy = await decodeRecoveryCode(code);
nextEntropy = (await generateRecoveryCode()).entropy;
await accounts.rotate({ handle, entropy: recoverEntropy, newPassphrase, nextEntropy });
({ token } = await accounts.signIn({ handle, passphrase: newPassphrase }));
} else {
const passphrase = $("passphrase").value;
if (!passphrase) return status("a passphrase is required", "error");
session = await Session.open({ api, passphrase, clearance });
({ token } = await accounts.signIn({ handle, passphrase }));
}
clearance = readClearance(token);
} catch (error) {
return status(error.message, "error");
}
const api = new EnclaveAPI({ token });
try {
if (mode === "recover") {
session = await Session.recover({
api,
code: $("recovery-code").value.trim(),
newPassphrase: $("new-passphrase").value,
clearance,
nextEntropy,
});
} else {
session = await Session.open({
api, passphrase: $("passphrase").value, clearance, recoveryEntropy: freshEntropy,
});
}
await session.loadLabelKeys();
@@ -252,7 +293,8 @@ async function upload(file) {
}
$("signin-button").onclick = signIn;
$("mode-toggle").onclick = () => setRecoveryMode(!recoveryMode);
$("mode-toggle").onclick = () => setMode(mode === "recover" ? "signin" : "recover");
$("register-toggle").onclick = () => setMode(mode === "register" ? "signin" : "register");
$("recovery-ack").onclick = () => {
// Held only in memory, and dropped as soon as it has been acknowledged.
session.recoveryCode = null;
+3 -2
View File
@@ -254,10 +254,11 @@ a { color: inherit; }
.footer-col a { display: block; text-decoration: none; color: var(--ink-2); font-size: 15px; margin-bottom: 9px; }
.footer-col a:hover { color: var(--brand); }
.footer-legal { border-top: 1px solid var(--border); padding-top: 26px; color: var(--ink-3); font-size: 14px; display: flex; flex-wrap: wrap; gap: 8px 20px; }
.hosted { margin-left: auto; }
.hosted { margin: 22px 0 0; padding-top: 20px; border-top: 1px solid var(--border);
text-align: center; color: var(--ink-3); font-size: 14px; }
.hosted a { color: var(--brand); font-weight: 650; text-decoration: none; }
.hosted a:hover { text-decoration: underline; }
@media (max-width: 620px) { .hosted { margin-left: 0; } }
.heart { color: #e0245e; font-style: normal; }
/* ---------- responsive ---------- */
+26 -3
View File
@@ -2,10 +2,33 @@
Open items, with their real blockers rather than optimistic ones.
## 1. FlameNet account service
## 1. FlameNet account service — built
One credential across FlameNet products. The cryptographic half is already
built: `deriveIdentityKEK` stretches the passphrase once and then derives a
Runs as its own binary in its own container, with its own database role granted
nothing outside `enclave_accounts`. It cannot read a single file row, and a
tenant role cannot read an account. The signed token is the entire interface.
- **Passphrase never reaches it.** The client derives an authentication secret
under `flamenet/files/auth/v1`, a different context from the encryption key,
so a fully compromised account service can impersonate you to itself and
decrypt nothing. There is a test for exactly that.
- **Product-scoped pseudonyms.** Each product server sees only
`HMAC(service_secret, account_id || product)`. The Files server never learns
the Messenger identifier.
- **No enumeration.** Asking for an unknown handle's stretch parameters returns
a deterministic fake derived from the service secret, indistinguishable from
a real one. Registration and login give the same answer either way.
- **No email column.** The privacy-maximal choice, and it makes operator-side
account recovery impossible by construction.
- **Clearance is granted by CLI**, never by an endpoint. There is no version of
granting a clearance that should be reachable from a browser session.
Still open: the Messenger side of the same service, and whether flamenet.io
links to it at all.
### Why the line sits where it does
The cryptographic half was already settled before this was built: `deriveIdentityKEK` stretches the passphrase once and then derives a
**separate key per product** under a distinct context string, so a compromise of
the Messenger identity key yields nothing about the Files identity key. Shared
login does not mean shared key material.
+4 -2
View File
@@ -7,6 +7,7 @@
<meta name="robots" content="noindex">
<link rel="stylesheet" href="/landing.css">
<link rel="stylesheet" href="/app.css">
<meta name="enclave-accounts" content="#(accountsURL)">
</head>
<body>
@@ -29,8 +30,8 @@
Your passphrase never leaves this tab. It builds the keys here, on your device.
</p>
<label class="field">
<span>Clearance token</span>
<input type="text" id="token" autocomplete="off" spellcheck="false">
<span>Handle</span>
<input type="text" id="handle" autocomplete="username" spellcheck="false">
</label>
<label class="field" id="passphrase-field">
<span>Passphrase</span>
@@ -47,6 +48,7 @@
</label>
<div class="toolbar" style="padding-bottom:0">
<button class="btn btn-primary btn-sm" id="signin-button">Unlock</button>
<button class="linkish" id="register-toggle">Create an account</button>
<button class="linkish" id="mode-toggle">I've lost my passphrase</button>
</div>
</section>
+5 -2
View File
@@ -90,9 +90,12 @@
<span>&copy; 2026 Extant 2000 LLC</span>
<span>MIT licensed</span>
<span>Files are encrypted in your browser before upload.</span>
<span class="hosted">Proudly hosted at
<a href="https://hitthosting.com">Hitt Hosting</a> &lt;3</span>
</div>
<p class="hosted">
Proudly hosted at <a href="https://hitthosting.com">Hitt Hosting</a>,
with <span class="heart" aria-label="love" role="img">&#10084;</span>
</p>
</div>
</footer>
@@ -0,0 +1,284 @@
import Crypto
import Fluent
import Foundation
import JWT
import Vapor
import EnclaveAuth
import EnclaveLattice
/// Registration, login, and token minting.
///
/// The server never sees a passphrase. The client stretches it and derives an
/// *authentication secret* under its own KDF context — a context distinct from
/// the one that produces the file-encryption key, so what arrives here can
/// never decrypt anything even if this service is fully compromised.
///
/// Because the client has already paid the expensive work factor, the server
/// only needs a salted fast hash to avoid storing a password-equivalent at
/// rest. Brute-forcing the stored verifier still means redoing the client's
/// 650,000-iteration stretch per guess.
struct AccountController: RouteCollection {
func boot(routes: any RoutesBuilder) throws {
let accounts = routes.grouped("accounts")
accounts.post(use: register)
accounts.get(":handle", "params", use: params)
accounts.post("rotate", use: rotate)
routes.post("sessions", use: session)
}
// MARK: types
struct RegisterRequest: Content {
let handle: String
/// Client-derived. Never the passphrase itself.
let authSecret: Data
let kdfSalt: Data
let kdfIterations: Int
/// Derived from the recovery code. Lets that code restore account
/// access as well as file access.
let recoveryAuthSecret: Data?
}
struct RotateRequest: Content {
let handle: String
/// Proof of the recovery code.
let recoveryAuthSecret: Data
let newAuthSecret: Data
let newKdfSalt: Data
let newKdfIterations: Int
/// Derived from the freshly issued code, since the old one is retired.
let newRecoveryAuthSecret: Data
}
struct ParamsResponse: Content {
let kdfSalt: Data
let kdfID: Int16
let kdfIterations: Int
}
struct SessionRequest: Content {
let handle: String
let authSecret: Data
let product: String?
let tenant: String?
}
struct SessionResponse: Content {
let token: String
let pseudonym: UUID
let expiresAt: Date
}
// MARK: helpers
static func normalize(handle: String) throws -> String {
let normalized = handle.trimmingCharacters(in: .whitespaces).lowercased()
let allowed = Set("abcdefghijklmnopqrstuvwxyz0123456789._-")
guard (2...63).contains(normalized.count),
let first = normalized.first, first.isLetter || first.isNumber,
normalized.allSatisfy(allowed.contains)
else {
throw Abort(.badRequest, reason: "handle must be 2-63 characters of a-z, 0-9, dot, dash or underscore")
}
return normalized
}
static func serviceSecret(_ app: Application) throws -> SymmetricKey {
guard let secret = Environment.get("ENCLAVE_ACCOUNTS_SECRET"), secret.count >= 32 else {
throw Abort(.internalServerError,
reason: "ENCLAVE_ACCOUNTS_SECRET is required and must be at least 32 characters")
}
return SymmetricKey(data: Data(secret.utf8))
}
/// A product-scoped identifier, derived rather than random so it can be
/// recomputed if a row is ever lost, and unlinkable without the secret.
static func pseudonym(accountID: UUID, product: String, secret: SymmetricKey) -> UUID {
var input = Data(accountID.uuidString.utf8)
input.append(Data("/\(product)".utf8))
let mac = HMAC<SHA256>.authenticationCode(for: input, using: secret)
var bytes = [UInt8](mac.prefix(16))
// Stamp RFC 4122 version 4 / variant bits so it is a well-formed UUID.
bytes[6] = (bytes[6] & 0x0F) | 0x40
bytes[8] = (bytes[8] & 0x3F) | 0x80
return UUID(uuid: (bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5],
bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11],
bytes[12], bytes[13], bytes[14], bytes[15]))
}
/// Byte comparison that does not short-circuit on the first difference.
static func constantTimeEquals(_ a: Data, _ b: Data) -> Bool {
guard a.count == b.count else { return false }
var difference: UInt8 = 0
for (x, y) in zip(a, b) { difference |= x ^ y }
return difference == 0
}
static func verifier(authSecret: Data, salt: Data) -> Data {
var hasher = SHA256()
hasher.update(data: salt)
hasher.update(data: authSecret)
return Data(hasher.finalize())
}
// MARK: handlers
func register(request: Request) async throws -> HTTPStatus {
let input = try request.content.decode(RegisterRequest.self)
let handle = try Self.normalize(handle: input.handle)
guard input.authSecret.count == 32 else {
throw Abort(.badRequest, reason: "authSecret must be 32 bytes")
}
guard input.kdfIterations >= 100_000 else {
throw Abort(.badRequest, reason: "kdfIterations is below the minimum work factor")
}
let secret = try Self.serviceSecret(request.application)
let verifierSalt = Data((0..<16).map { _ in UInt8.random(in: 0...255) })
let account = AccountModel()
account.handle = handle
account.kdfSalt = input.kdfSalt
account.kdfID = 1
account.kdfIterations = input.kdfIterations
account.verifierSalt = verifierSalt
account.verifier = Self.verifier(authSecret: input.authSecret, salt: verifierSalt)
if let recovery = input.recoveryAuthSecret {
let salt = Data((0..<16).map { _ in UInt8.random(in: 0...255) })
account.recoveryVerifierSalt = salt
account.recoveryVerifier = Self.verifier(authSecret: recovery, salt: salt)
}
do {
try await account.create(on: request.db)
} catch {
// Unique violation. Reported the same as any other rejection so the
// endpoint is not a handle-enumeration oracle.
throw Abort(.conflict, reason: "that handle is not available")
}
let accountID = try account.requireID()
for product in ["files", "messenger"] {
try await AccountProductModel(
accountID: accountID,
product: product,
pseudonym: Self.pseudonym(accountID: accountID, product: product, secret: secret)
).create(on: request.db)
}
return .created
}
/// The client needs the stretch parameters before it can log in.
///
/// An unknown handle gets a *deterministic* fake, derived from the service
/// secret, so this endpoint cannot be used to enumerate who has an account:
/// the same unknown handle always returns the same plausible salt, and a
/// real one is indistinguishable from it.
func params(request: Request) async throws -> ParamsResponse {
let handle = try Self.normalize(handle: request.parameters.get("handle") ?? "")
if let account = try await AccountModel.query(on: request.db)
.filter(\.$handle == handle).first() {
return ParamsResponse(
kdfSalt: account.kdfSalt, kdfID: account.kdfID, kdfIterations: account.kdfIterations
)
}
let secret = try Self.serviceSecret(request.application)
let mac = HMAC<SHA256>.authenticationCode(for: Data("salt/\(handle)".utf8), using: secret)
return ParamsResponse(kdfSalt: Data(mac.prefix(16)), kdfID: 1, kdfIterations: 650_000)
}
/// Re-establish account access with a recovery code, and set a new
/// passphrase. The file-side recovery happens separately in the browser;
/// both must succeed for the account to be usable again.
func rotate(request: Request) async throws -> HTTPStatus {
let input = try request.content.decode(RotateRequest.self)
let handle = try Self.normalize(handle: input.handle)
guard input.newKdfIterations >= 100_000 else {
throw Abort(.badRequest, reason: "newKdfIterations is below the minimum work factor")
}
let account = try await AccountModel.query(on: request.db)
.filter(\.$handle == handle).first()
guard let account,
let storedSalt = account.recoveryVerifierSalt,
let stored = account.recoveryVerifier,
Self.constantTimeEquals(
Self.verifier(authSecret: input.recoveryAuthSecret, salt: storedSalt), stored
)
else {
// Same answer whether the handle is unknown, has no recovery code,
// or the code is wrong.
throw Abort(.unauthorized, reason: "handle or recovery code is incorrect")
}
let verifierSalt = Data((0..<16).map { _ in UInt8.random(in: 0...255) })
account.kdfSalt = input.newKdfSalt
account.kdfIterations = input.newKdfIterations
account.verifierSalt = verifierSalt
account.verifier = Self.verifier(authSecret: input.newAuthSecret, salt: verifierSalt)
let recoverySalt = Data((0..<16).map { _ in UInt8.random(in: 0...255) })
account.recoveryVerifierSalt = recoverySalt
account.recoveryVerifier = Self.verifier(authSecret: input.newRecoveryAuthSecret, salt: recoverySalt)
try await account.update(on: request.db)
return .ok
}
func session(request: Request) async throws -> SessionResponse {
let input = try request.content.decode(SessionRequest.self)
let handle = try Self.normalize(handle: input.handle)
let product = input.product ?? "files"
let tenant = input.tenant ?? Environment.get("ENCLAVE_TENANT") ?? "default"
let account = try await AccountModel.query(on: request.db)
.filter(\.$handle == handle).first()
// Same message and comparable work whether the handle exists or not.
guard let account,
Self.constantTimeEquals(
Self.verifier(authSecret: input.authSecret, salt: account.verifierSalt),
account.verifier
)
else {
throw Abort(.unauthorized, reason: "handle or passphrase is incorrect")
}
let accountID = try account.requireID()
let secret = try Self.serviceSecret(request.application)
let pseudonym = Self.pseudonym(accountID: accountID, product: product, secret: secret)
// Absent an assignment, clearance is the bottom of the lattice. A new
// account sees nothing until someone grants it something.
let assigned = try await ClearanceModel.query(on: request.db)
.filter(\.$id == accountID)
.filter(\.$product == product)
.filter(\.$tenant == tenant)
.first()
let clearance = Clearance(
maximum: Label(
classification: Classification(assigned?.maxClass ?? 0),
compartments: Compartments(postgresBitPattern: assigned?.maxComp ?? 0)
),
minimum: Label(
classification: Classification(assigned?.minClass ?? 0),
compartments: Compartments(postgresBitPattern: assigned?.minComp ?? 0)
)
)
let lifetime = Double(Environment.get("ENCLAVE_TOKEN_HOURS").flatMap(Int.init) ?? 12) * 3600
let expiresAt = Date().addingTimeInterval(lifetime)
let token = EnclaveToken(
pseudonym: pseudonym, tenant: tenant, clearance: clearance, expiresAt: expiresAt
)
return SessionResponse(
token: try await request.application.jwt.keys.sign(token),
pseudonym: pseudonym,
expiresAt: expiresAt
)
}
}
+142
View File
@@ -0,0 +1,142 @@
import Fluent
import FluentPostgresDriver
import Foundation
import JWT
import Logging
import SQLKit
import Vapor
import EnclaveAuth
import EnclaveLattice
@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()
}
}
func configure(_ app: Application) async throws {
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)
// The same secret the file server verifies with. This service is the only
// one that signs.
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)
_ = try AccountController.serviceSecret(app)
// The browser calls this service from the application's origin, which is a
// different host in production. Origins are listed explicitly rather than
// reflected, so a page on any other site cannot drive it.
let allowed = (Environment.get("ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS") ?? "")
.split(separator: ",").map { String($0).trimmingCharacters(in: .whitespaces) }
.filter { !$0.isEmpty }
if !allowed.isEmpty {
app.middleware.use(CORSMiddleware(configuration: .init(
allowedOrigin: .any(allowed),
allowedMethods: [.GET, .POST, .OPTIONS],
allowedHeaders: [.accept, .authorization, .contentType, .origin]
)))
}
app.migrations.add(InstallAccountsSchema())
if Environment.get("ENCLAVE_AUTO_MIGRATE") == "true" {
try await app.autoMigrate()
}
app.asyncCommands.use(GrantCommand(), as: "grant")
app.get("healthz") { _ async -> String in "ok" }
try app.register(collection: AccountController())
}
/// Fluent's schema builder cannot express the constraints this table needs, so
/// the DDL lives in a .sql file and the migration executes it verbatim.
struct InstallAccountsSchema: AsyncMigration {
var name: String { "InstallAccountsSchema" }
func prepare(on database: any Database) async throws {
guard let sql = database as? any SQLDatabase else { return }
guard let url = Bundle.module.url(forResource: "SQL/010_accounts", withExtension: "sql") else {
throw Abort(.internalServerError, reason: "missing bundled SQL resource")
}
try await sql.raw(.init(try String(contentsOf: url, encoding: .utf8))).run()
// The service connects as this role, so it needs LOGIN. Deliberately
// not a superuser and granted nothing outside its own schema.
if let password = Environment.get("ENCLAVE_ACCOUNTS_DB_PASSWORD"), !password.isEmpty {
try await sql.raw(
"SELECT enclave_accounts.set_role_login('accounts_service', \(bind: password))"
).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_accounts CASCADE").run()
}
}
/// Assign clearance to an account.
///
/// Deliberately a command rather than an endpoint: granting someone a clearance
/// is an administrative act, and there is no version of it that should be
/// reachable from a browser session.
struct GrantCommand: AsyncCommand {
struct Signature: CommandSignature {
@Option(name: "handle", help: "Account handle.") var handle: String?
@Option(name: "product", help: "Product. Defaults to 'files'.") var product: String?
@Option(name: "tenant", help: "Tenant slug. Defaults to ENCLAVE_TENANT or 'default'.") var tenant: String?
@Option(name: "max-class", help: "Maximum classification ordinal.") var maxClass: Int?
@Option(name: "max-comp", help: "Comma-separated compartment bits, e.g. 0,1.") var maxComp: String?
}
var help: String { "Assign a clearance to an account." }
func run(using context: CommandContext, signature: Signature) async throws {
guard let handle = try signature.handle.map(AccountController.normalize(handle:)) else {
throw Abort(.badRequest, reason: "--handle is required")
}
let db = context.application.db
guard let account = try await AccountModel.query(on: db).filter(\.$handle == handle).first() else {
throw Abort(.notFound, reason: "no account with handle '\(handle)'")
}
let bits = (signature.maxComp ?? "").split(separator: ",").compactMap { Int($0.trimmingCharacters(in: .whitespaces)) }
for bit in bits where !(0...63).contains(bit) {
throw Abort(.badRequest, reason: "compartment bit \(bit) is not in 0...63")
}
let product = signature.product ?? "files"
let tenant = signature.tenant ?? Environment.get("ENCLAVE_TENANT") ?? "default"
let accountID = try account.requireID()
let existing = try await ClearanceModel.query(on: db)
.filter(\.$id == accountID).filter(\.$product == product).filter(\.$tenant == tenant).first()
let row = existing ?? ClearanceModel(accountID: accountID, product: product, tenant: tenant)
row.maxClass = Int16(signature.maxClass ?? 0)
row.maxComp = Compartments(bits: bits).postgresBitPattern
if existing == nil { try await row.create(on: db) } else { try await row.update(on: db) }
context.console.print("granted \(handle) → \(product)/\(tenant): classification \(row.maxClass), compartments \(bits)")
}
}
@@ -0,0 +1,60 @@
import Fluent
import Foundation
final class AccountModel: Model, @unchecked Sendable {
static let schema = "accounts"
@ID(key: .id) var id: UUID?
@Field(key: "handle") var handle: String
@Field(key: "kdf_salt") var kdfSalt: Data
@Field(key: "kdf_id") var kdfID: Int16
@Field(key: "kdf_iterations") var kdfIterations: Int
@Field(key: "verifier_salt") var verifierSalt: Data
@Field(key: "verifier") var verifier: Data
@OptionalField(key: "recovery_verifier") var recoveryVerifier: Data?
@OptionalField(key: "recovery_verifier_salt") var recoveryVerifierSalt: Data?
@Timestamp(key: "created_at", on: .create) var createdAt: Date?
init() {}
}
final class AccountProductModel: Model, @unchecked Sendable {
static let schema = "account_products"
// Composite primary key; Fluent addresses the row by the pair.
@ID(custom: "account_id", generatedBy: .user) var id: UUID?
@Field(key: "product") var product: String
@Field(key: "pseudonym") var pseudonym: UUID
init() {}
init(accountID: UUID, product: String, pseudonym: UUID) {
self.id = accountID
self.product = product
self.pseudonym = pseudonym
}
}
final class ClearanceModel: Model, @unchecked Sendable {
static let schema = "clearances"
@ID(custom: "account_id", generatedBy: .user) var id: UUID?
@Field(key: "product") var product: String
@Field(key: "tenant") var tenant: String
@Field(key: "max_class") var maxClass: Int16
@Field(key: "max_comp") var maxComp: Int64
@Field(key: "min_class") var minClass: Int16
@Field(key: "min_comp") var minComp: Int64
init() {}
init(accountID: UUID, product: String, tenant: String) {
self.id = accountID
self.product = product
self.tenant = tenant
self.maxClass = 0
self.maxComp = 0
self.minClass = 0
self.minComp = 0
}
}
@@ -0,0 +1,97 @@
-- The shared FlameNet account service.
--
-- Its own schema and its own role, with no grant on any tenant schema. The file
-- server cannot read accounts and the account service cannot read files; the
-- signed token is the entire interface between them.
--
-- Deliberately small. Every column here is a column that exists in a breach, in
-- a log, and in a subpoena, so the table holds an opaque id, a login handle, and
-- what is needed to check a password -- and nothing else. There is no email
-- column: omitting it is the privacy-maximal choice and it makes account
-- recovery impossible, which is a trade the operator should make knowingly.
CREATE SCHEMA IF NOT EXISTS enclave_accounts;
CREATE TABLE IF NOT EXISTS enclave_accounts.accounts (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
handle text UNIQUE NOT NULL CHECK (handle ~ '^[a-z0-9][a-z0-9._-]{1,62}$'),
-- Parameters the *client* uses to stretch the passphrase. Handed out before
-- login, so they are not secret; they are per-account so one leaked table
-- cannot be attacked with a single precomputed set.
kdf_salt bytea NOT NULL,
kdf_id smallint NOT NULL DEFAULT 1,
kdf_iterations integer NOT NULL,
-- What the server compares against. The client sends an authentication
-- secret derived from the passphrase under its own context, so this value
-- can never decrypt anything, and the expensive work factor has already
-- been paid on the client before it arrives.
verifier_salt bytea NOT NULL,
verifier bytea NOT NULL,
-- The same recovery code that unlocks the file key also re-establishes
-- account access. Without this, recovering would decrypt your files and
-- still leave you unable to sign in — the code must cover both secrets or
-- it covers neither usefully.
--
-- The code carries 128 bits of its own entropy, so this derivation needs no
-- passphrase stretching: HKDF over the code is enough, and the server keeps
-- only a salted hash of the result.
recovery_verifier bytea,
recovery_verifier_salt bytea,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Product-scoped pseudonyms. Each product server sees only its own identifier
-- for a person and cannot correlate its users with another product's. The
-- account service can, which is exactly why it stores so little else.
CREATE TABLE IF NOT EXISTS enclave_accounts.account_products (
account_id uuid NOT NULL REFERENCES enclave_accounts.accounts(id) ON DELETE CASCADE,
product text NOT NULL CHECK (product IN ('files', 'messenger')),
pseudonym uuid NOT NULL,
PRIMARY KEY (account_id, product),
UNIQUE (product, pseudonym)
);
-- Clearance is assigned here, never asserted by a client. The file server reads
-- it only from a signed token.
CREATE TABLE IF NOT EXISTS enclave_accounts.clearances (
account_id uuid NOT NULL REFERENCES enclave_accounts.accounts(id) ON DELETE CASCADE,
product text NOT NULL,
tenant text NOT NULL,
max_class smallint NOT NULL DEFAULT 0,
max_comp bigint NOT NULL DEFAULT 0,
min_class smallint NOT NULL DEFAULT 0,
min_comp bigint NOT NULL DEFAULT 0,
PRIMARY KEY (account_id, product, tenant)
);
-- The service role. Fixed name, so a literal in DDL is safe here.
--
-- It is granted USAGE on this schema only. It has no grant on any tenant
-- schema, so a compromised account service cannot read a single file row —
-- and conversely a tenant role has no grant here. The signed token is the
-- entire interface between the two.
CREATE OR REPLACE FUNCTION enclave_accounts.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$;
DO $$
BEGIN
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'accounts_service') THEN
CREATE ROLE accounts_service NOLOGIN;
END IF;
END
$$;
REVOKE ALL ON SCHEMA enclave_accounts FROM PUBLIC;
GRANT USAGE ON SCHEMA enclave_accounts TO accounts_service;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA enclave_accounts TO accounts_service;
GRANT EXECUTE ON FUNCTION enclave_accounts.set_role_login(text, text) TO accounts_service;
ALTER ROLE accounts_service SET search_path = enclave_accounts;
+103
View File
@@ -0,0 +1,103 @@
import Foundation
import JWT
import Vapor
import EnclaveLattice
/// Clearance travels in a signed token, not in a database lookup.
///
/// Shared between the account service, which mints these, and the file server,
/// which only verifies them. Neither can reach the other's tables: the account
/// service has no grant on any tenant schema, and a tenant role has no grant on
/// the account schema. The token is the entire interface between them.
///
/// 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.
public struct EnclaveToken: JWTPayload {
public 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"
}
public var subject: SubjectClaim
public var expiration: ExpirationClaim
public var tenant: String
// Clearance bounds, flattened so the token stays small.
public var maxClassification: Int16
public var maxCompartments: Int64
public var minClassification: Int16
public var minCompartments: Int64
public init(
subject: SubjectClaim,
expiration: ExpirationClaim,
tenant: String,
maxClassification: Int16,
maxCompartments: Int64,
minClassification: Int16,
minCompartments: Int64
) {
self.subject = subject
self.expiration = expiration
self.tenant = tenant
self.maxClassification = maxClassification
self.maxCompartments = maxCompartments
self.minClassification = minClassification
self.minCompartments = minCompartments
}
public func verify(using algorithm: some JWTAlgorithm) async throws {
try expiration.verifyNotExpired()
}
public 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
}
}
public var clearance: Clearance {
Clearance(
maximum: Label(
classification: Classification(maxClassification),
compartments: Compartments(postgresBitPattern: maxCompartments)
),
minimum: Label(
classification: Classification(minClassification),
compartments: Compartments(postgresBitPattern: minCompartments)
)
)
}
}
extension EnclaveToken {
/// Build a token from a product-scoped pseudonym and a clearance.
public init(
pseudonym: UUID,
tenant: String,
clearance: Clearance,
expiresAt: Date
) {
self.init(
subject: .init(value: pseudonym.uuidString),
expiration: .init(value: expiresAt),
tenant: tenant,
maxClassification: clearance.maximum.classification.rawValue,
maxCompartments: clearance.maximum.compartments.postgresBitPattern,
minClassification: clearance.minimum.classification.rawValue,
minCompartments: clearance.minimum.compartments.postgresBitPattern
)
}
}
@@ -1,59 +0,0 @@
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)
)
)
}
}
@@ -2,6 +2,7 @@ import Foundation
import JWT
import Vapor
import EnclaveLattice
import EnclaveAuth
import EnclaveAccess
/// Everything a request is allowed to do, resolved once at the edge.
@@ -2,6 +2,7 @@ import Foundation
import JWT
import Vapor
import EnclaveLattice
import EnclaveAuth
/// Mint a clearance token, for development only.
///
@@ -17,12 +17,20 @@ struct SiteController: RouteCollection {
Environment.get("ENCLAVE_APP_URL") ?? "/app"
}
/// Where the browser reaches the shared account service. A different origin
/// in production, which is why that service lists allowed origins
/// explicitly rather than reflecting whatever asks.
static var accountsURL: String {
Environment.get("ENCLAVE_ACCOUNTS_URL") ?? "http://127.0.0.1:8100"
}
struct PageContext: Encodable {
let title: String
let description: String
let path: String
let siteURL: String
let appURL: String
let accountsURL: String
init(title: String, description: String, path: String) {
self.title = title
@@ -30,6 +38,7 @@ struct SiteController: RouteCollection {
self.path = path
self.siteURL = SiteController.siteURL
self.appURL = SiteController.appURL
self.accountsURL = SiteController.accountsURL
}
}
+116
View File
@@ -0,0 +1,116 @@
import { b64, unb64, random, utf8 } from "./bytes.js";
import { KDF_PBKDF2_V1, deriveAuthSecret } from "./kdf.js";
import { kdfSecret } from "./recovery.js";
/**
* The account-side half of a recovery code.
*
* The code already carries 128 bits of its own entropy, so this needs no
* passphrase stretching and no salt round-trip — HKDF over the code is enough,
* and the server keeps only a salted hash of the result.
*/
async function recoveryAuthSecret(entropy) {
const base = await crypto.subtle.importKey(
"raw", utf8(kdfSecret(entropy)), "HKDF", false, ["deriveBits"]
);
const bits = await crypto.subtle.deriveBits(
{
name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0),
info: utf8("flamenet/files/auth-recovery/v1"),
},
base, 256
);
return new Uint8Array(bits);
}
/**
* Client for the shared FlameNet account service.
*
* One credential across products, with no shared key material: the secret this
* sends is derived under an authentication context, while the key that opens
* files is derived under an encryption context from the same passphrase. A
* compromised account service can impersonate you to itself and decrypt
* nothing.
*
* The passphrase never leaves the browser in either case.
*/
export class AccountsAPI {
constructor(baseURL = "") {
this.baseURL = baseURL.replace(/\/$/, "");
}
async #json(method, path, body) {
const response = await fetch(`${this.baseURL}${path}`, {
method,
headers: body ? { "Content-Type": "application/json" } : {},
body: body ? JSON.stringify(body) : undefined,
});
if (!response.ok) {
let reason = `${response.status}`;
try { reason = (await response.json()).reason ?? reason; } catch { /* non-JSON body */ }
throw new Error(reason);
}
return response.status === 204 ? null : response.json();
}
/**
* Stretch parameters for a handle.
*
* An unknown handle returns a deterministic fake, so this cannot be used to
* discover who has an account — and the client cannot tell the difference,
* which is the point.
*/
params(handle) {
return this.#json("GET", `/accounts/${encodeURIComponent(handle.toLowerCase())}/params`);
}
/**
* Register, binding the recovery code to the account as well as to the
* files. A code that restored file access but left you unable to sign in
* would not be a recovery mechanism.
*/
async register({ handle, passphrase, recoveryEntropy }) {
const kdfSalt = random(KDF_PBKDF2_V1.saltBytes);
const authSecret = await deriveAuthSecret(passphrase, kdfSalt, { params: KDF_PBKDF2_V1 });
await this.#json("POST", "/accounts", {
handle: handle.toLowerCase(),
authSecret: b64(authSecret),
kdfSalt: b64(kdfSalt),
kdfIterations: KDF_PBKDF2_V1.iterations,
recoveryAuthSecret: recoveryEntropy ? b64(await recoveryAuthSecret(recoveryEntropy)) : null,
});
}
/**
* Prove the recovery code and set a new passphrase.
*
* `nextEntropy` is the freshly issued code: the old one is retired here as
* well as on the file side, so a code that has already been used somewhere
* does not stay live.
*/
async rotate({ handle, entropy, newPassphrase, nextEntropy }) {
const kdfSalt = random(KDF_PBKDF2_V1.saltBytes);
const newAuthSecret = await deriveAuthSecret(newPassphrase, kdfSalt, { params: KDF_PBKDF2_V1 });
await this.#json("POST", "/accounts/rotate", {
handle: handle.toLowerCase(),
recoveryAuthSecret: b64(await recoveryAuthSecret(entropy)),
newAuthSecret: b64(newAuthSecret),
newKdfSalt: b64(kdfSalt),
newKdfIterations: KDF_PBKDF2_V1.iterations,
newRecoveryAuthSecret: b64(await recoveryAuthSecret(nextEntropy)),
});
}
/** Returns a clearance token for the file server. */
async signIn({ handle, passphrase, product = "files" }) {
const params = await this.params(handle);
const authSecret = await deriveAuthSecret(passphrase, unb64(params.kdfSalt), {
params: { ...KDF_PBKDF2_V1, iterations: params.kdfIterations },
});
return this.#json("POST", "/sessions", {
handle: handle.toLowerCase(),
authSecret: b64(authSecret),
product,
});
}
}
+41
View File
@@ -49,6 +49,19 @@ export function kdfParams(id) {
return params;
}
/**
* Authentication contexts.
*
* The secret sent to the account service is derived from the same passphrase as
* the encryption key, but under a *different* context — so a fully compromised
* account service holds something that can log in as you and nothing that can
* decrypt a single file. The two derivations are cryptographically unrelated.
*/
export const AUTH_CONTEXT = Object.freeze({
files: "flamenet/files/auth/v1",
messenger: "flamenet/messenger/auth/v1",
});
/** Stage one: the expensive stretch. Shared across products, never used directly. */
async function deriveMaster(passphrase, salt, params) {
if (params.id !== 1) throw new Error(`KDF id ${params.id} is not implemented`);
@@ -78,3 +91,31 @@ export async function deriveIdentityKEK(passphrase, salt, {
["encrypt", "decrypt"]
);
}
/**
* Raw key bytes for a context, rather than a CryptoKey.
*
* Used for the authentication secret, which is sent to the account service. The
* expensive stretch happens here, on the client, so the server can store a
* plain salted hash: brute-forcing it still costs an attacker the full
* iteration count per guess.
*/
export async function deriveBytes(passphrase, salt, {
params = KDF_PBKDF2_V1,
context,
length = 32,
} = {}) {
if (!context) throw new Error("a context string is required");
const master = await deriveMaster(passphrase, salt, params);
const base = await crypto.subtle.importKey("raw", master, "HKDF", false, ["deriveBits"]);
const bits = await crypto.subtle.deriveBits(
{ name: "HKDF", hash: "SHA-256", salt: new Uint8Array(0), info: utf8(context) },
base,
length * 8
);
return new Uint8Array(bits);
}
export const deriveAuthSecret = (passphrase, salt, options = {}) =>
deriveBytes(passphrase, salt, { ...options, context: options.context ?? AUTH_CONTEXT.files });
+13 -5
View File
@@ -4,7 +4,9 @@ import {
generateIdentity, protectIdentity, unlockIdentity, exportPublicKey,
protectIdentityWithRecovery, unlockWithRecovery,
} from "./identity.js";
import { generateRecoveryCode, decode as decodeRecoveryCode } from "./recovery.js";
import {
generateRecoveryCode, decode as decodeRecoveryCode, encode as encodeRecoveryCode,
} from "./recovery.js";
import {
createLabelKey, createNodeKey, createContentKey,
grantLabelKey, acceptLabelKey, wrapNodeKey, unwrapNodeKey,
@@ -45,7 +47,7 @@ export class Session {
* exists anywhere. It is not stored, not derivable from the passphrase, and
* cannot be reissued -- only replaced by rekeying with a known secret.
*/
static async open({ api, passphrase, clearance }) {
static async open({ api, passphrase, clearance, recoveryEntropy = null }) {
// The identity endpoints are label-gated like everything else, so a
// label must be set before the first call. The clearance minimum is
// always assertable.
@@ -62,7 +64,11 @@ export class Session {
}
const pair = await generateIdentity();
const { entropy, code } = await generateRecoveryCode();
// Supplied by the caller when the same code must also register with the
// account service; generated here otherwise.
const { entropy, code } = recoveryEntropy
? { entropy: recoveryEntropy, code: await encodeRecoveryCode(recoveryEntropy) }
: await generateRecoveryCode();
const [record, recovery] = await Promise.all([
protectIdentity(pair.privateKey, passphrase),
protectIdentityWithRecovery(pair.privateKey, entropy),
@@ -86,7 +92,7 @@ export class Session {
* issued and the old one stops working, because leaving a code in play that
* the user has already had cause to use somewhere is the wrong default.
*/
static async recover({ api, code, newPassphrase, clearance }) {
static async recover({ api, code, newPassphrase, clearance, nextEntropy = null }) {
api.setLabel(clearance.minimum);
const existing = await api.get("/api/identity");
@@ -100,7 +106,9 @@ export class Session {
"raw", unb64(existing.publicKey), "X25519", true, []
);
const next = await generateRecoveryCode();
const next = nextEntropy
? { entropy: nextEntropy, code: await encodeRecoveryCode(nextEntropy) }
: await generateRecoveryCode();
const [record, recovery] = await Promise.all([
protectIdentity(privateKey, newPassphrase),
protectIdentityWithRecovery(privateKey, next.entropy),
+20
View File
@@ -89,3 +89,23 @@ test("a different recovery code does not unlock", async () => {
const record = await protectIdentityWithRecovery(pair.privateKey, entropy, { params: FAST });
await assert.rejects(() => unlockWithRecovery(record, other.entropy));
});
// The property the shared account service rests on.
test("the authentication secret cannot decrypt anything", async () => {
const { deriveAuthSecret, deriveIdentityKEK, CONTEXT } = await import("../src/kdf.js");
const salt = crypto.getRandomValues(new Uint8Array(16));
const options = { params: FAST };
const authSecret = await deriveAuthSecret("one passphrase", salt, options);
const encryptionKEK = await deriveIdentityKEK("one passphrase", salt, {
...options, context: CONTEXT.files,
});
// Seal something with the encryption key, then try the value the server holds.
const nonce = new Uint8Array(12);
const sealed = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv: nonce }, encryptionKEK, new TextEncoder().encode("secret")
);
const asKey = await crypto.subtle.importKey("raw", authSecret, { name: "AES-GCM" }, false, ["decrypt"]);
await assert.rejects(() => crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce }, asKey, sealed));
});
+42 -2
View File
@@ -32,6 +32,41 @@ services:
restart: unless-stopped
# Deliberately not published to the host. Reach it with `docker compose exec db psql`.
# The shared FlameNet account service. Its own container and its own database
# role, granted nothing outside enclave_accounts — so it cannot read a single
# file row, and the file server cannot read an account. The signed token is
# the entire interface between them.
accounts-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_ACCOUNTS_SECRET: ${ENCLAVE_ACCOUNTS_SECRET:?set ENCLAVE_ACCOUNTS_SECRET in .env}
ENCLAVE_ACCOUNTS_DB_PASSWORD: ${ENCLAVE_ACCOUNTS_DB_PASSWORD:?set ENCLAVE_ACCOUNTS_DB_PASSWORD in .env}
command: ["./EnclaveAccounts", "migrate", "--yes"]
restart: "no"
accounts:
build: .
depends_on:
accounts-migrate:
condition: service_completed_successfully
environment:
DATABASE_URL: postgres://accounts_service:${ENCLAVE_ACCOUNTS_DB_PASSWORD}@db:5432/enclave
ENCLAVE_JWT_SECRET: ${ENCLAVE_JWT_SECRET}
ENCLAVE_ACCOUNTS_SECRET: ${ENCLAVE_ACCOUNTS_SECRET}
ENCLAVE_TENANT: ${ENCLAVE_TENANT:-default}
# Listed explicitly rather than reflected, so no other page can drive it.
ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS: ${ENCLAVE_ACCOUNTS_ALLOWED_ORIGINS:-http://127.0.0.1:8080,http://localhost:8080}
LOG_LEVEL: ${LOG_LEVEL:-info}
command: ["./EnclaveAccounts", "serve", "--env", "production", "--hostname", "0.0.0.0", "--port", "8100"]
ports:
- "${ENCLAVE_BIND:-127.0.0.1}:${ENCLAVE_ACCOUNTS_PORT:-8100}:8100"
restart: unless-stopped
migrate:
build: .
depends_on:
@@ -42,7 +77,7 @@ services:
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"]
command: ["./EnclaveServer", "migrate", "--yes"]
restart: "no"
app:
@@ -56,6 +91,11 @@ services:
ENCLAVE_JWT_SECRET: ${ENCLAVE_JWT_SECRET}
ENCLAVE_TENANT: ${ENCLAVE_TENANT:-default}
ENCLAVE_BLOB_PATH: /app/blobs
# Where the browser reaches the account service. A different origin, so
# the app page carries it and that service allow-lists this one.
ENCLAVE_ACCOUNTS_URL: ${ENCLAVE_ACCOUNTS_URL:-http://127.0.0.1:8100}
ENCLAVE_SITE_URL: ${ENCLAVE_SITE_URL:-http://127.0.0.1:8080}
ENCLAVE_APP_URL: ${ENCLAVE_APP_URL:-/app}
LOG_LEVEL: ${LOG_LEVEL:-info}
volumes:
# Ciphertext blobs. Without this the files themselves live only in the
@@ -63,7 +103,7 @@ services:
# leaving every node row pointing at nothing.
- enclave-blobs:/app/blobs
ports:
- "${ENCLAVE_BIND:-127.0.0.1}:8080:8080"
- "${ENCLAVE_BIND:-127.0.0.1}:${ENCLAVE_PORT:-8080}:8080"
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8080/healthz || exit 1"]
interval: 15s