Bento, the office suite that fits in a file
TypeScript mit-licenseofficeoffice-365office-suiteoffice-toolsoffice365open-sourcepowerpointself-hostedsingle-page-appslidesslideshareslideshowslideshow-galleryslideshow-makerslideshows
home/ios: refuse an Argon2id derivation cleanly when the process lacks the memory (#795)
nyblnetbe2605d265af
diff --git a/home/ios/Argon2id.swift b/home/ios/Argon2id.swiftindex c374d67a..457f9ac0 100644--- a/home/ios/Argon2id.swift+++ b/home/ios/Argon2id.swift@@ -2,6 +2,7 @@// Copyright (c) 2026 The Bento authorsimport Foundation+import os/// Argon2id (RFC 9106, version 0x13), which neither CryptoKit nor CommonCrypto/// has. It stretches a recovery code into its keys (kernel/src/recovery.ts).@@ -28,10 +29,51 @@ enum Argon2id {/// security §28: p = 1, 64 MiB, t = 3, a 32-byte tagstatic let bento = Params(memoryKiB: 65536, passes: 3, parallelism: 1, tagLength: 32)+ // MARK: - memory++ /// Past what it was given, iOS ends the process outright (jetsam): there is+ /// no failed allocation to catch, and Swift's allocate never returns nil. So+ /// the memory is checked BEFORE anything is allocated, and a derivation the+ /// process can't afford is refused cleanly.+ static let headroom = 32 << 20++ /// the blocks a derivation fills, plus headroom+ static func memoryNeeded(_ params: Params) -> Int {+ let p = params.parallelism+ return 4 * p * (params.memoryKiB / (4 * p)) * 1024 + headroom+ }++ /// How much more this process may allocate before iOS ends it. nil where+ /// there's no such limit: the simulator and the Mac.+ static func platformAvailableMemory() -> Int? {+ #if os(iOS) && !targetEnvironment(simulator) && !targetEnvironment(macCatalyst)+ return Int(os_proc_available_memory())+ #else+ return nil+ #endif+ }++ #if DEBUG || BENTO_WIPE_PROBE+ /// Replaceable in DEBUG and rig builds only, so the rig can stand in a+ /// low-memory device. A release build can't swap the reading.+ nonisolated(unsafe) static var availableMemory: () -> Int? = platformAvailableMemory+ #else+ static let availableMemory: () -> Int? = platformAvailableMemory+ #endif++ /// Whether a derivation with these parameters can run now: what the UI asks+ /// so it can say why a recovery can't go ahead.+ static func hasMemory(for params: Params = bento) -> Bool {+ guard let free = availableMemory() else { return true }+ return free >= memoryNeeded(params)+ }++ /// The tag, or nil when this process can't afford the memory right now.static func hash(password: [UInt8], salt: [UInt8], secret: [UInt8] = [], ad: [UInt8] = [],- params: Params = bento) -> [UInt8] {+ params: Params = bento) -> [UInt8]? {let p = params.parallelism, t = params.passesprecondition(p >= 1 && t >= 1 && params.tagLength >= 4 && params.memoryKiB >= 8 * p)+ guard hasMemory(for: params) else { return nil }let mPrime = 4 * p * (params.memoryKiB / (4 * p))let laneLen = mPrime / p, segLen = laneLen / 4diff --git a/home/ios/IdentityRecovery.swift b/home/ios/IdentityRecovery.swiftindex 53260cdc..fcdf5593 100644--- a/home/ios/IdentityRecovery.swift+++ b/home/ios/IdentityRecovery.swift@@ -80,10 +80,11 @@ enum IdentityRecovery {return k.withUnsafeBytes { Array($0) }}- /// the recovery blob's wrap key: HKDF(Argon2id(code, salt), empty, "bento/id/rc-wrap/v1")+ /// the recovery blob's wrap key: HKDF(Argon2id(code, salt), empty, "bento/id/rc-wrap/v1").+ /// nil for a malformed input, or when Argon2id.hasMemory() says nostatic func recoveryWrapKey(code: [UInt8], salt: [UInt8]) -> [UInt8]? {guard code.count == codeBytes, salt.count == saltLength else { return nil }- var stretched = Argon2id.hash(password: code, salt: salt)+ guard var stretched = Argon2id.hash(password: code, salt: salt) else { return nil } // no memory for itdefer { Argon2id.wipe(&stretched) }return hkdf(stretched, info: "bento/id/rc-wrap/v1")}diff --git a/scripts/test-home-id-recovery.mjs b/scripts/test-home-id-recovery.mjsindex 911833a1..3e86215f 100644--- a/scripts/test-home-id-recovery.mjs+++ b/scripts/test-home-id-recovery.mjs@@ -57,6 +57,7 @@ typealias R = IdentityRecoveryfunc hx(_ s: String) -> [UInt8] { var o: [UInt8] = []; var i = s.startIndex; while i < s.endIndex { let j = s.index(i, offsetBy: 2); o.append(UInt8(s[i..<j], radix: 16)!); i = j }; return o }func hs(_ b: [UInt8]?) -> String { b.map { $0.map { String(format: "%02x", $0) }.joined() } ?? "nil" }func emit(_ k: String, _ v: Any) { print("\(k)=\(v)") }+func code10() -> [UInt8] { hx("009e01a578034a5304ef") }func j(_ path: String) -> Any { try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path))) }func verdict<T>(_ v: R.Verdict<T>, _ show: (T) -> String) -> String { switch v { case .ok(let x): return "ok:" + show(x); case .no(let r): return "no:" + r } }let F = j(CommandLine.arguments[1]) as! [String: Any]@@ -80,6 +81,22 @@ _ = Argon2id.hash(password: hx("009e01a578034a5304ef"), salt: hx("10111213141516Argon2id.probe = nilemit("wipe", "\(released)|\(largest)|\(dirty)")+// memory: refused BEFORE anything is allocated when the process can't afford it+released = 0+Argon2id.probe = { _, _ in released += 1 }+Argon2id.availableMemory = { 48 << 20 }+let low = Argon2id.hash(password: code10(), salt: hx("101112131415161718191a1b1c1d1e1f"))+let lowWrap = R.recoveryWrapKey(code: code10(), salt: hx("101112131415161718191a1b1c1d1e1f"))+emit("mem.low", "\(low == nil)|\(lowWrap == nil)|\(released)|\(Argon2id.hasMemory())")+Argon2id.availableMemory = { Argon2id.memoryNeeded(Argon2id.bento) }+emit("mem.edge", Argon2id.hash(password: code10(), salt: hx("101112131415161718191a1b1c1d1e1f")).map(hs) ?? "nil")+Argon2id.availableMemory = { Argon2id.memoryNeeded(Argon2id.bento) - 1 }+emit("mem.short1", Argon2id.hash(password: code10(), salt: hx("101112131415161718191a1b1c1d1e1f")) == nil)+Argon2id.availableMemory = { nil }+emit("mem.nolimit", Argon2id.hasMemory())+emit("mem.needed", Argon2id.memoryNeeded(Argon2id.bento))+Argon2id.probe = nil+// codes and parsingfor (i, c) in (F["codes"] as! [[String: Any]]).enumerated() { emit("fmt\(i)", R.formatCode(hx(c["bytes"] as! String)) ?? "nil") }for (i, c) in (F["parse"] as! [[String: Any]]).enumerated() { emit("parse\(i)", verdict(R.parseCode(c["input"] as! String)) { hs($0) }) }@@ -166,6 +183,16 @@ console.log(` (64 MiB, t = 3 took ${out.argon2_ms} ms here)`)const [released, largest, dirty] = (out.wipe ?? '').split('|').map(Number)ok(released >= 6 && largest === 65536 * 128 && dirty === 0, `every buffer is zeroed before it's freed, the 64 MiB of blocks included (${released} buffers, ${dirty} not zeroed)`)}+console.log('memory (iOS ends a process past its limit; nothing to catch):')+{+ const [lowNil, wrapNil, released, has] = (out['mem.low'] ?? '').split('|')+ ok(lowNil === 'true' && wrapNil === 'true' && has === 'false', 'with 48 MiB free, Argon2id and the wrap key refuse, and hasMemory() says so')+ ok(released === '0', 'and nothing was allocated first (no buffer was ever released)')+ ok(out['mem.edge'] === F.derivations.argon2_A, 'with exactly 64 MiB + headroom free it runs, and gives the fixture\'s bytes')+ ok(out['mem.short1'] === 'true', 'one byte short of that: refused')+ ok(out['mem.nolimit'] === 'true', 'where there is no limit (the simulator, the Mac), it runs')+ ok(Number(out['mem.needed']) === 64 * 1024 * 1024 + 32 * 1024 * 1024, `it asks for the 64 MiB of blocks plus 32 MiB headroom (${out['mem.needed']})`)+}console.log('the recovery code:')F.codes.forEach((c, i) => ok(out[`fmt${i}`] === c.printed, `${c.bytes} prints as ${c.printed}`))F.parse.forEach((p, i) => {