ReviewOS

also looking at this

craft-native/craft

feat(android): the secure-storage quartet — ratchet 95 -> 91

#147
Merged chris wants to merge feat/android-secure-storage into main
6 files +501 -3
packages/zig/src/bridge_android_securestore.zigadded+303-0
Changes to packages/zig/src/bridge_android_securestore.zig
@@ -0,0 +1,303 @@
1//! The Android secure-storage quartet: `secureSet`, `secureGet`,
2//! `secureRemove`, `secureClear`.
3//!
4//! ## Kotlin passes the store; Zig does not build one
5//!
6//! Every other action here reaches its platform object through the `Activity`.
7//! These four do not, and the difference is deliberate. `securePrefs` is
8//!
9//! EncryptedSharedPreferences.create(activity, "craft_secure_prefs",
10//! masterKey, AES256_SIV, AES256_GCM)
11//!
12//! over a lazily-built `MasterKey`. Zig could construct that — it is two
13//! builder calls and two enum constants — and constructing it would be a
14//! mistake. It is a second implementation of a security-sensitive
15//! construction, in a second language, that has to agree with the first
16//! exactly: a different key scheme, a different file name, a different SIV
17//! mode, and the two halves write data neither can read. Nothing would fail
18//! at build time and the symptom would be a user's saved token disappearing
19//! after an app update.
20//!
21//! So the native methods take the `SharedPreferences` as a parameter. The
22//! object is Kotlin's, the lifetime is Kotlin's, and Zig only ever calls the
23//! plain `SharedPreferences` interface on it — which is the whole of what the
24//! Kotlin does too, since `EncryptedSharedPreferences` *is* a
25//! `SharedPreferences` and the encryption is behind the interface.
26//!
27//! This generalises: where the shim already holds a configured platform
28//! object, handing it across the seam beats rebuilding it.
29//!
30//! ## `secureGet` has three answers where the others have two
31//!
32//! The Kotlin returns `String?`, and null there means "no such key". The seam
33//! also needs to say "Zig did not serve this" — and a nullable String cannot
34//! carry both, because an absent key and a declined call are different things
35//! and the caller must do different things about them.
36//!
37//! There is no spare value to steal: `""` is a legitimate stored value, and so
38//! is any sentinel a caller could also have saved. So the reply is an envelope,
39//! `{"found":…}`, and null is reserved for "declined". Three states, three
40//! representations, none of them overloaded.
41
42const std = @import("std");
43const jni = @import("jni_runtime.zig");
44const bridge_error = @import("bridge_error.zig");
45
46const Jni = jni.Jni;
47const jobject = jni.jobject;
48
49pub const A = struct {
50 pub const secure_set = "secureSet";
51 pub const secure_get = "secureGet";
52 pub const secure_remove = "secureRemove";
53 pub const secure_clear = "secureClear";
54};
55
56/// `prefs.edit()` — the editor every write goes through.
57///
58/// `SharedPreferences.Editor` is an inner interface, so its binary name
59/// carries the `$`: `android/content/SharedPreferences$Editor`.
60fn editor(j: Jni, prefs: jobject) !jobject {
61 const prefs_cls = try j.objectClass(prefs);
62 return j.callObjectMethod(
63 prefs,
64 try j.methodId(prefs_cls, "edit", "()Landroid/content/SharedPreferences$Editor;"),
65 );
66}
67
68/// `edit.apply()`.
69///
70/// `apply` rather than `commit`, matching the Kotlin. It writes to memory
71/// synchronously and to disk on a background thread, and returns void — so a
72/// disk failure is invisible to both implementations, and "true" here means
73/// the edit was accepted rather than persisted. Switching to `commit` would
74/// make Zig report a truth the shim does not, which is a divergence even when
75/// it is an improvement.
76fn apply(j: Jni, edit: jobject) !void {
77 const edit_cls = try j.objectClass(edit);
78 try j.callVoidMethodA(edit, try j.methodId(edit_cls, "apply", "()V"), &.{});
79}
80
81pub fn set(j: Jni, prefs: jobject, key: [*:0]const u8, value: [*:0]const u8) !void {
82 try j.pushLocalFrame(16);
83 defer _ = j.popLocalFrame(null);
84
85 const edit = try editor(j, prefs);
86 const edit_cls = try j.objectClass(edit);
87
88 _ = try j.callObjectMethodA(
89 edit,
90 try j.methodId(
91 edit_cls,
92 "putString",
93 "(Ljava/lang/String;Ljava/lang/String;)Landroid/content/SharedPreferences$Editor;",
94 ),
95 &.{ .{ .l = try j.newStringUtf(key) }, .{ .l = try j.newStringUtf(value) } },
96 );
97 try apply(j, edit);
98}
99
100pub fn remove(j: Jni, prefs: jobject, key: [*:0]const u8) !void {
101 try j.pushLocalFrame(16);
102 defer _ = j.popLocalFrame(null);
103
104 const edit = try editor(j, prefs);
105 const edit_cls = try j.objectClass(edit);
106
107 _ = try j.callObjectMethodA(
108 edit,
109 try j.methodId(edit_cls, "remove", "(Ljava/lang/String;)Landroid/content/SharedPreferences$Editor;"),
110 &.{.{ .l = try j.newStringUtf(key) }},
111 );
112 try apply(j, edit);
113}
114
115pub fn clear(j: Jni, prefs: jobject) !void {
116 try j.pushLocalFrame(16);
117 defer _ = j.popLocalFrame(null);
118
119 const edit = try editor(j, prefs);
120 const edit_cls = try j.objectClass(edit);
121
122 _ = try j.callObjectMethodA(
123 edit,
124 try j.methodId(edit_cls, "clear", "()Landroid/content/SharedPreferences$Editor;"),
125 &.{},
126 );
127 try apply(j, edit);
128}
129
130/// The reply envelope for `secureGet`. See the module comment for why a bare
131/// nullable string cannot carry these three states.
132pub fn renderRead(allocator: std.mem.Allocator, value: ?[]const u8) ![]u8 {
133 var out: std.ArrayListUnmanaged(u8) = .empty;
134 errdefer out.deinit(allocator);
135
136 if (value) |text| {
137 try out.appendSlice(allocator, "{\"found\":true,\"value\":\"");
138 // The quotes are this caller's job — `appendJsonEscaped` escapes the
139 // contents and writes no delimiters. A stored value containing a quote
140 // would otherwise tear the envelope and read back as absent.
141 try bridge_error.appendJsonEscaped(allocator, &out, text);
142 try out.appendSlice(allocator, "\"}");
143 } else {
144 try out.appendSlice(allocator, "{\"found\":false}");
145 }
146 return out.toOwnedSlice(allocator);
147}
148
149/// `prefs.getString(key, null)`, as an owned optional. Caller frees.
150pub fn get(allocator: std.mem.Allocator, j: Jni, prefs: jobject, key: [*:0]const u8) !?[]u8 {
151 try j.pushLocalFrame(16);
152 defer _ = j.popLocalFrame(null);
153
154 const prefs_cls = try j.objectClass(prefs);
155 const value = try j.callObjectMethodA(
156 prefs,
157 try j.methodId(
158 prefs_cls,
159 "getString",
160 "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
161 ),
162 // The default is null, which is what makes "absent" distinguishable
163 // from a stored empty string.
164 &.{ .{ .l = try j.newStringUtf(key) }, .{ .l = null } },
165 );
166 if (value == null) return null;
167 return try j.stringToUtf8(allocator, value);
168}
169
170// =============================================================================
171// Tests
172// =============================================================================
173
174const testing = std.testing;
175
176test "the read envelope distinguishes absent from empty" {
177 // The whole reason the envelope exists. A stored `""` and a missing key
178 // are different, and a bare nullable string collapses them the moment the
179 // seam also needs to say "declined".
180 const absent = try renderRead(testing.allocator, null);
181 defer testing.allocator.free(absent);
182 const empty = try renderRead(testing.allocator, "");
183 defer testing.allocator.free(empty);
184
185 var a = try std.json.parseFromSlice(std.json.Value, testing.allocator, absent, .{});
186 defer a.deinit();
187 var e = try std.json.parseFromSlice(std.json.Value, testing.allocator, empty, .{});
188 defer e.deinit();
189
190 try testing.expectEqual(false, a.value.object.get("found").?.bool);
191 try testing.expect(a.value.object.get("value") == null);
192
193 try testing.expectEqual(true, e.value.object.get("found").?.bool);
194 try testing.expectEqualStrings("", e.value.object.get("value").?.string);
195}
196
197test "a stored value containing a quote does not tear the envelope" {
198 // Secure storage holds tokens, and a JWT is base64 — but nothing stops a
199 // page storing arbitrary text, and `appendJsonEscaped` writes no
200 // delimiters of its own. The same trap that broke the iOS
201 // location-recording state file.
202 const json = try renderRead(testing.allocator, "a\"b\\c\nd");
203 defer testing.allocator.free(json);
204
205 var p = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
206 defer p.deinit();
207 try testing.expectEqual(true, p.value.object.get("found").?.bool);
208 try testing.expectEqualStrings("a\"b\\c\nd", p.value.object.get("value").?.string);
209}
210
211test "the action names match the Kotlin methods exactly" {
212 try testing.expectEqualStrings("secureSet", A.secure_set);
213 try testing.expectEqualStrings("secureGet", A.secure_get);
214 try testing.expectEqualStrings("secureRemove", A.secure_remove);
215 try testing.expectEqualStrings("secureClear", A.secure_clear);
216}
217
218// --- A fake SharedPreferences ---------------------------------------------
219//
220// `renderRead` above tests the envelope, and the envelope is only half the
221// decision: whether a key is absent is settled in `get`, against
222// `getString(key, null)`. A mutation returning `""` for an absent key passed
223// every test in this file until these were written — the same shape of gap the
224// envelope exists to close, one layer down.
225
226var fake_storage: [8]u8 = undefined;
227var fake_value_present = true;
228
229fn sobj(tag: usize) jobject {
230 return @ptrCast(&fake_storage[tag]);
231}
232fn sObjectClass(_: jni.JNIEnv, _: jobject) callconv(.c) jni.jclass {
233 return sobj(0);
234}
235fn sMethodId(_: jni.JNIEnv, _: jni.jclass, name: [*:0]const u8, _: [*:0]const u8) callconv(.c) jni.jmethodID {
236 return @ptrCast(@constCast(name));
237}
238fn sNewStringUTF(_: jni.JNIEnv, _: [*:0]const u8) callconv(.c) jni.jstring {
239 return sobj(1);
240}
241fn sCallObjectMethodA(_: jni.JNIEnv, _: jobject, _: jni.jmethodID, args: [*]const jni.jvalue) callconv(.c) jobject {
242 // `getString(key, null)` — the second argument is the default, and the
243 // fake honours it rather than inventing one, because "the default comes
244 // back" is precisely the absent case.
245 if (!fake_value_present) return args[1].l;
246 return sobj(2);
247}
248fn sGetStringUTFChars(_: jni.JNIEnv, _: jni.jstring, _: ?*jni.jboolean) callconv(.c) ?[*:0]const u8 {
249 return "stored";
250}
251fn sReleaseStringUTFChars(_: jni.JNIEnv, _: jni.jstring, _: [*:0]const u8) callconv(.c) void {}
252fn sExceptionOccurred(_: jni.JNIEnv) callconv(.c) jobject {
253 return null;
254}
255fn sPush(_: jni.JNIEnv, _: jni.jint) callconv(.c) jni.jint {
256 return 0;
257}
258fn sPop(_: jni.JNIEnv, keep: jobject) callconv(.c) jobject {
259 return keep;
260}
261
262fn getWith(present: bool) !?[]u8 {
263 fake_value_present = present;
264 var table = std.mem.zeroes(jni.JNINativeInterface);
265 table.GetObjectClass = @ptrCast(&sObjectClass);
266 table.GetMethodID = @ptrCast(&sMethodId);
267 table.NewStringUTF = @ptrCast(&sNewStringUTF);
268 table.CallObjectMethodA = @ptrCast(&sCallObjectMethodA);
269 table.GetStringUTFChars = @ptrCast(&sGetStringUTFChars);
270 table.ReleaseStringUTFChars = @ptrCast(&sReleaseStringUTFChars);
271 table.ExceptionOccurred = @ptrCast(&sExceptionOccurred);
272 table.PushLocalFrame = @ptrCast(&sPush);
273 table.PopLocalFrame = @ptrCast(&sPop);
274
275 const ptr: *const jni.JNINativeInterface = &table;
276 return get(testing.allocator, Jni.init(&ptr), sobj(3), "token");
277}
278
279test "an absent key reads as null, never as an empty string" {
280 // The mutation this was written for: returning `""` here instead of null
281 // makes every missing key look like a stored empty string, and the
282 // envelope then reports `found: true` for something that was never saved.
283 const absent = try getWith(false);
284 try testing.expect(absent == null);
285
286 const present = try getWith(true);
287 defer if (present) |p| testing.allocator.free(p);
288 try testing.expect(present != null);
289 try testing.expectEqualStrings("stored", present.?);
290}
291
292test "the absent case survives the round trip through the envelope" {
293 // End to end, because the two halves are only correct together: a `get`
294 // that loses the distinction and a `renderRead` that keeps it still
295 // produce `{"found":true}` for a key nobody stored.
296 const absent = try getWith(false);
297 const json = try renderRead(testing.allocator, absent);
298 defer testing.allocator.free(json);
299
300 var p = try std.json.parseFromSlice(std.json.Value, testing.allocator, json, .{});
301 defer p.deinit();
302 try testing.expectEqual(false, p.value.object.get("found").?.bool);
303}