Mint one token per relay with iss, aud and jti (todo 370)

POST /sessions/relay trades a session token for a 5 minute token naming
one relay. Session tokens are unchanged, so shipped apps keep working.
A token with aud is refused as a session here and at the file server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1
2026-11-13 14:44:52 -05:00
co-authored by Claude Opus 5.5
parent 02d5a60d87
commit 594234c263
4 changed files with 152 additions and 0 deletions
+1
View File
@@ -39,6 +39,7 @@ service on port 8100. It needs `ENCLAVE_JWT_SECRET` and
| `POST /accounts/rotate` | Re-establish access with a recovery code. |
| `POST /accounts/delete` | Delete an account and everything keyed to it. |
| `POST /sessions` | Sign in. Returns the signed token a relay verifies. |
| `POST /sessions/relay` | Bearer session. Body `{"audience": <relay FN_RELAY_AUDIENCE>}`. Returns a 5 minute token for that one relay with `iss`, `aud` and a fresh `jti`. Refused here and at the file server as a session. |
| `GET /.well-known/jwks.json` | The public half, so a relay can verify without being able to mint. |
| `GET` / `POST /identity` | Read or enrol a per-product identity record. Enrolment is optional and nothing currently uses it. |
| `POST /identity/rekey` | Re-wrap an identity record under a new passphrase. |
@@ -27,6 +27,46 @@ struct AccountController: RouteCollection {
accounts.post("passphrase", use: changePassphrase)
accounts.post("delete", use: destroy)
routes.post("sessions", use: session)
routes.post("sessions", "relay", use: relaySession)
}
struct RelaySessionRequest: Content {
/// The relay's `FN_RELAY_AUDIENCE`, its public base URL.
let audience: String
}
struct RelaySessionResponse: Content {
let token: String
let expiresAt: Date
}
/// The `iss` stamped on relay tokens, and what a relay sets as
/// `FN_ACCOUNT_TOKEN_ISSUER`.
static var relayIssuer: String {
let configured = Environment.get("ENCLAVE_TOKEN_ISSUER")?
.trimmingCharacters(in: .whitespaces) ?? ""
return configured.isEmpty ? "https://accounts.flamenet.io" : configured
}
/// Trade a session token for a token minted for one relay.
///
/// The session token is the bearer. The answer carries `iss`, `aud` (the
/// relay named here) and a fresh `jti`, lives five minutes at most, and is
/// refused by this service and the file server, so a relay that keeps it
/// gains nothing here. Sessions themselves are unchanged, so app builds
/// that send a session token straight to a relay keep working.
func relaySession(request: Request) async throws -> RelaySessionResponse {
let session = try await request.jwt.verify(as: EnclaveToken.self)
let input = try request.content.decode(RelaySessionRequest.self)
let audience = input.audience.trimmingCharacters(in: .whitespacesAndNewlines)
guard !audience.isEmpty, audience.count <= 256 else {
throw Abort(.badRequest, reason: "audience must be 1 to 256 characters")
}
let token = session.forRelay(audience: audience, issuer: Self.relayIssuer)
return RelaySessionResponse(
token: try await request.application.jwt.keys.sign(
token, kid: request.application.storage[SessionKeys.SigningKeyID.self]),
expiresAt: token.expiration.value)
}
// MARK: types
+43
View File
@@ -26,6 +26,9 @@ public struct EnclaveToken: JWTPayload {
case minCompartments = "mnk"
case device = "dev"
case devices = "devs"
case issuer = "iss"
case audiences = "aud"
case id = "jti"
}
public var subject: SubjectClaim
@@ -71,6 +74,16 @@ public struct EnclaveToken: JWTPayload {
/// failure this is willing to have rather than an unbounded header.
public var devices: [String]?
/// `iss`, `aud` and `jti`, set only on a relay token (`forRelay`).
///
/// Optional for the same reason `dev` is: sessions minted before these
/// existed have none and must keep decoding. A session token never carries
/// them, because one session token is sent to several relays and a `jti`
/// can be traded only once at each.
public var issuer: String?
public var audiences: [String]?
public var id: String?
public init(
subject: SubjectClaim,
expiration: ExpirationClaim,
@@ -95,6 +108,36 @@ public struct EnclaveToken: JWTPayload {
public func verify(using algorithm: some JWTAlgorithm) async throws {
try expiration.verifyNotExpired()
// A relay token is handed to a relay, which may be run by somebody
// else. It must not work as a session here or at the file server.
if audiences != nil {
throw JWTError.claimVerificationFailure(
failedClaim: nil, reason: "a relay token is not a session")
}
}
/// How long a relay token lives: one exchange, so minutes.
public static let relayLifetime: TimeInterval = 300
/// One token for one relay, minted from a verified session.
///
/// Same `sub` and clearance as the session, so the relay sees the same
/// pseudonym it always has. `aud` names the one relay, `iss` the account
/// service, and `jti` is fresh, so the relay can refuse a token minted for
/// another relay or traded twice. The device list stays behind: a relay
/// has no use for it.
public func forRelay(
audience: String, issuer: String, id: String = UUID().uuidString, now: Date = Date()
) -> EnclaveToken {
var token = self
token.expiration = .init(
value: min(expiration.value, now.addingTimeInterval(Self.relayLifetime)))
token.device = nil
token.devices = nil
token.issuer = issuer
token.audiences = [audience]
token.id = id
return token
}
public var principalID: UUID {
@@ -0,0 +1,68 @@
import XCTest
import JWT
import EnclaveLattice
@testable import EnclaveAuth
/// Relay tokens: one per relay, with `iss`, `aud` and `jti`.
final class RelayTokenTests: XCTestCase {
private let clearance = Clearance(
maximum: Label(classification: Classification(3), compartments: Compartments()),
minimum: Label(classification: Classification(0), compartments: Compartments()))
private func session(hours: Double = 12) -> EnclaveToken {
EnclaveToken(pseudonym: UUID(), tenant: "t", clearance: clearance,
expiresAt: Date().addingTimeInterval(hours * 3600),
device: "phone-1", devices: ["phone-1", "laptop-2"])
}
func testARelayTokenCarriesTheThreeClaims() throws {
let s = session()
let r = s.forRelay(audience: "https://relay.example", issuer: "https://accounts.example")
let body = try JSONSerialization.jsonObject(
with: JSONEncoder().encode(r)) as! [String: Any]
XCTAssertEqual(body["iss"] as? String, "https://accounts.example")
XCTAssertEqual(body["aud"] as? [String], ["https://relay.example"])
XCTAssertFalse((body["jti"] as? String ?? "").isEmpty)
XCTAssertEqual(body["sub"] as? String, s.subject.value)
XCTAssertNil(body["dev"])
XCTAssertNil(body["devs"])
}
func testEachRelayTokenHasAFreshJTI() {
let s = session()
let a = s.forRelay(audience: "https://a", issuer: "i")
let b = s.forRelay(audience: "https://a", issuer: "i")
XCTAssertNotEqual(a.id, b.id)
}
func testARelayTokenLivesFiveMinutesAtMost() {
let now = Date()
let long = session().forRelay(audience: "a", issuer: "i", now: now)
XCTAssertEqual(long.expiration.value.timeIntervalSince(now), 300, accuracy: 1)
let short = session(hours: 1.0 / 3600).forRelay(audience: "a", issuer: "i", now: now)
XCTAssertLessThan(short.expiration.value.timeIntervalSince(now), 2)
}
/// A session token carries none of the three, so every relay that takes it
/// today keeps taking it.
func testASessionTokenCarriesNoRelayClaims() throws {
let body = String(decoding: try JSONEncoder().encode(session()), as: UTF8.self)
XCTAssertFalse(body.contains("\"aud\""))
XCTAssertFalse(body.contains("\"jti\""))
XCTAssertFalse(body.contains("\"iss\""))
}
/// A relay could replay what it was given; here it is not a session.
func testARelayTokenIsRefusedAsASession() async throws {
let keys = JWTKeyCollection()
await keys.add(hmac: HMACKey(stringLiteral: String(repeating: "k", count: 32)), digestAlgorithm: .sha256)
let relay = try await keys.sign(session().forRelay(audience: "a", issuer: "i"))
do {
_ = try await keys.verify(relay, as: EnclaveToken.self)
XCTFail("a relay token verified as a session")
} catch {}
let plain = try await keys.sign(session())
_ = try await keys.verify(plain, as: EnclaveToken.self)
}
}