Repository navigation
Expand file tree
/
Copy pathauth.zig
More file actions
943 lines (798 loc) · 34.7 KB
/
Copy pathauth.zig
File metadata and controls
943 lines (798 loc) · 34.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
//! Unified OAuth 2.0 module — PKCE, device code flow, credential store.
//!
//! Provides reusable OAuth primitives for all providers:
//! - PKCE challenge generation (RFC 7636)
//! - Token storage with filesystem-based credential store (auth.json in the config directory)
//! - Device Authorization Grant flow (RFC 8628)
const std = @import("std");
const std_compat = @import("compat");
const config_paths = @import("config_paths.zig");
const fs_compat = @import("fs_compat.zig");
const http_util = @import("http_util.zig");
const json_util = @import("json_util.zig");
// ── PKCE (RFC 7636) ────────────────────────────────────────────────────
pub const PkceChallenge = struct {
verifier: []u8,
challenge: []u8,
method: []const u8 = "S256",
pub fn deinit(self: PkceChallenge, allocator: std.mem.Allocator) void {
allocator.free(self.verifier);
allocator.free(self.challenge);
}
};
/// Generate a PKCE challenge pair (RFC 7636).
/// 64 random bytes → base64url (no padding) verifier.
/// SHA-256(verifier) → base64url (no padding) challenge.
pub fn generatePkce(allocator: std.mem.Allocator) !PkceChallenge {
var random_bytes: [64]u8 = undefined;
std_compat.crypto.random.bytes(&random_bytes);
// base64url-encode the random bytes → verifier (86 chars for 64 bytes, no padding)
const verifier = try base64UrlEncodeAlloc(allocator, &random_bytes);
errdefer allocator.free(verifier);
// SHA-256(verifier) → challenge
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(verifier, &hash, .{});
const challenge = try base64UrlEncodeAlloc(allocator, &hash);
return .{
.verifier = verifier,
.challenge = challenge,
};
}
/// Base64url-encode without padding, returning an allocated slice.
fn base64UrlEncodeAlloc(allocator: std.mem.Allocator, input: []const u8) ![]u8 {
const Encoder = std.base64.url_safe_no_pad.Encoder;
const len = Encoder.calcSize(input.len);
const buf = try allocator.alloc(u8, len);
_ = Encoder.encode(buf, input);
return buf;
}
// ── OAuth Token ────────────────────────────────────────────────────────
pub const OAuthToken = struct {
access_token: []const u8,
refresh_token: ?[]const u8 = null,
expires_at: i64 = 0,
token_type: []const u8 = "Bearer",
/// Returns true if the token is expired or within 300s of expiring.
pub fn isExpired(self: OAuthToken) bool {
if (self.expires_at == 0) return false;
return std_compat.time.timestamp() + 300 >= self.expires_at;
}
/// Free all heap-allocated fields. Only call on tokens returned by
/// parseTokenResponse / loadCredential / startDeviceCodeFlow (i.e. tokens
/// whose string fields were produced by allocator.dupe).
pub fn deinit(self: OAuthToken, allocator: std.mem.Allocator) void {
allocator.free(self.access_token);
if (self.refresh_token) |rt| allocator.free(rt);
// token_type is heap-allocated when parsed from JSON responses
allocator.free(self.token_type);
}
};
// ── Credential Store ───────────────────────────────────────────────────
const CRED_FILE = "auth.json";
fn credentialFilePathFromConfigDir(allocator: std.mem.Allocator, config_dir: []const u8) ![]u8 {
return config_paths.pathFromConfigDir(allocator, config_dir, CRED_FILE);
}
fn credentialFilePath(allocator: std.mem.Allocator) ![]u8 {
const config_dir = try config_paths.defaultConfigDir(allocator);
defer allocator.free(config_dir);
return credentialFilePathFromConfigDir(allocator, config_dir);
}
fn writeCredentialsFileAtomic(file_path: []const u8, contents: []const u8) !void {
fs_compat.writeFileAtomicSecure(file_path, contents) catch return error.CredentialWriteFailed;
}
/// Save a credential for the given provider to auth.json in the config directory.
/// Merges with existing credentials (other providers are preserved).
/// File permissions are set to 0o600.
pub fn saveCredential(allocator: std.mem.Allocator, provider: []const u8, token: OAuthToken) !void {
const file_path = credentialFilePath(allocator) catch |err| switch (err) {
error.HomeDirNotFound => return error.HomeNotSet,
else => return err,
};
defer allocator.free(file_path);
// Ensure directory exists
const dir_path = std_compat.fs.path.dirname(file_path) orelse return error.CredentialWriteFailed;
fs_compat.makePath(dir_path) catch return error.CredentialWriteFailed;
// Read existing credentials (if any)
var existing = loadAllCredentials(allocator, file_path) orelse std.StringHashMap(StoredToken).init(allocator);
defer {
var it = existing.iterator();
while (it.next()) |entry| {
allocator.free(entry.key_ptr.*);
freeStoredToken(allocator, entry.value_ptr.*);
}
existing.deinit();
}
// Upsert provider entry.
// After put() succeeds, the map owns these allocations and the defer
// block above handles cleanup. The flag prevents errdefer double-frees
// if a subsequent try (serialization / file I/O) fails.
var put_succeeded = false;
const key_owned = try allocator.dupe(u8, provider);
errdefer if (!put_succeeded) allocator.free(key_owned);
if (existing.fetchRemove(key_owned)) |old| {
allocator.free(old.key);
freeStoredToken(allocator, old.value);
}
const at_owned = try allocator.dupe(u8, token.access_token);
errdefer if (!put_succeeded) allocator.free(at_owned);
const rt_owned: ?[]const u8 = if (token.refresh_token) |rt| try allocator.dupe(u8, rt) else null;
errdefer {
if (!put_succeeded) {
if (rt_owned) |rt| allocator.free(rt);
}
}
const tt_owned = try allocator.dupe(u8, token.token_type);
errdefer if (!put_succeeded) allocator.free(tt_owned);
try existing.put(key_owned, .{
.access_token = at_owned,
.refresh_token = rt_owned,
.expires_at = token.expires_at,
.token_type = tt_owned,
});
put_succeeded = true;
// Serialize
var buf: std.ArrayListUnmanaged(u8) = .empty;
defer buf.deinit(allocator);
try buf.append(allocator, '{');
var first = true;
var iter = existing.iterator();
while (iter.next()) |entry| {
if (!first) try buf.append(allocator, ',');
first = false;
try json_util.appendJsonKey(&buf, allocator, entry.key_ptr.*);
try buf.append(allocator, '{');
try json_util.appendJsonKeyValue(&buf, allocator, "access_token", entry.value_ptr.*.access_token);
if (entry.value_ptr.*.refresh_token) |rt| {
try buf.append(allocator, ',');
try json_util.appendJsonKeyValue(&buf, allocator, "refresh_token", rt);
}
try buf.append(allocator, ',');
try json_util.appendJsonInt(&buf, allocator, "expires_at", entry.value_ptr.*.expires_at);
try buf.append(allocator, ',');
try json_util.appendJsonKeyValue(&buf, allocator, "token_type", entry.value_ptr.*.token_type);
try buf.append(allocator, '}');
}
try buf.append(allocator, '}');
try writeCredentialsFileAtomic(file_path, buf.items);
}
/// Load a credential for the given provider from auth.json in the config directory.
/// Returns null if the file is missing, the provider is not found, or the token
/// is expired and cannot be refreshed.
pub fn loadCredential(allocator: std.mem.Allocator, provider: []const u8) !?OAuthToken {
const file_path = credentialFilePath(allocator) catch return null;
defer allocator.free(file_path);
const file = fs_compat.openPath(file_path, .{}) catch return null;
defer file.close();
const json_bytes = file.readToEndAlloc(allocator, 1024 * 1024) catch return null;
defer allocator.free(json_bytes);
const parsed = std.json.parseFromSlice(std.json.Value, allocator, json_bytes, .{}) catch return null;
defer parsed.deinit();
const root_obj = switch (parsed.value) {
.object => |obj| obj,
else => return null,
};
const provider_val = root_obj.get(provider) orelse return null;
const prov_obj = switch (provider_val) {
.object => |obj| obj,
else => return null,
};
const access_token_val = prov_obj.get("access_token") orelse return null;
const access_token_str = switch (access_token_val) {
.string => |s| s,
else => return null,
};
if (access_token_str.len == 0) return null;
const access_token = try allocator.dupe(u8, access_token_str);
errdefer allocator.free(access_token);
const refresh_token: ?[]const u8 = if (prov_obj.get("refresh_token")) |rt_val| blk: {
switch (rt_val) {
.string => |s| break :blk if (s.len > 0) try allocator.dupe(u8, s) else null,
else => break :blk null,
}
} else null;
errdefer if (refresh_token) |rt| allocator.free(rt);
const expires_at: i64 = if (prov_obj.get("expires_at")) |ea_val| blk: {
switch (ea_val) {
.integer => |i| break :blk i,
.float => |f| break :blk @intFromFloat(f),
else => break :blk 0,
}
} else 0;
const token_type_raw: []const u8 = if (prov_obj.get("token_type")) |tt_val| blk: {
switch (tt_val) {
.string => |s| break :blk s,
else => break :blk "Bearer",
}
} else "Bearer";
const token_type = try allocator.dupe(u8, token_type_raw);
errdefer allocator.free(token_type);
if (expires_at != 0 and std_compat.time.timestamp() + 300 >= expires_at and refresh_token == null) {
allocator.free(access_token);
if (refresh_token) |rt| allocator.free(rt);
allocator.free(token_type);
return null;
}
return OAuthToken{
.access_token = access_token,
.refresh_token = refresh_token,
.expires_at = expires_at,
.token_type = token_type,
};
}
const StoredToken = struct {
access_token: []const u8,
refresh_token: ?[]const u8,
expires_at: i64,
token_type: []const u8,
};
fn freeStoredToken(allocator: std.mem.Allocator, tok: StoredToken) void {
allocator.free(tok.access_token);
if (tok.refresh_token) |rt| allocator.free(rt);
allocator.free(tok.token_type);
}
fn loadAllCredentials(allocator: std.mem.Allocator, file_path: []const u8) ?std.StringHashMap(StoredToken) {
const file = fs_compat.openPath(file_path, .{}) catch return null;
defer file.close();
const json_bytes = file.readToEndAlloc(allocator, 1024 * 1024) catch return null;
defer allocator.free(json_bytes);
const parsed = std.json.parseFromSlice(std.json.Value, allocator, json_bytes, .{}) catch return null;
defer parsed.deinit();
const root_obj = switch (parsed.value) {
.object => |obj| obj,
else => return null,
};
var map = std.StringHashMap(StoredToken).init(allocator);
var it = root_obj.iterator();
while (it.next()) |entry| {
const prov_obj = switch (entry.value_ptr.*) {
.object => |obj| obj,
else => continue,
};
const at = switch (prov_obj.get("access_token") orelse continue) {
.string => |s| s,
else => continue,
};
const rt: ?[]const u8 = if (prov_obj.get("refresh_token")) |v| switch (v) {
.string => |s| if (s.len > 0) s else null,
else => null,
} else null;
const ea: i64 = if (prov_obj.get("expires_at")) |v| switch (v) {
.integer => |i| i,
.float => |f| @as(i64, @intFromFloat(f)),
else => 0,
} else 0;
const tt: []const u8 = if (prov_obj.get("token_type")) |v| switch (v) {
.string => |s| s,
else => "Bearer",
} else "Bearer";
const key = allocator.dupe(u8, entry.key_ptr.*) catch continue;
const access_token = allocator.dupe(u8, at) catch {
allocator.free(key);
continue;
};
const refresh_token = if (rt) |r| allocator.dupe(u8, r) catch null else null;
const token_type = allocator.dupe(u8, tt) catch {
allocator.free(key);
allocator.free(access_token);
if (refresh_token) |owned_rt| allocator.free(owned_rt);
continue;
};
map.put(key, .{
.access_token = access_token,
.refresh_token = refresh_token,
.expires_at = ea,
.token_type = token_type,
}) catch {
allocator.free(token_type);
if (refresh_token) |owned_rt| allocator.free(owned_rt);
allocator.free(access_token);
allocator.free(key);
continue;
};
}
return map;
}
// ── Token Refresh ─────────────────────────────────────────────────────
/// Refresh an OAuth access token using a refresh_token grant.
/// Preserves the old refresh_token if the response omits a new one.
pub fn refreshAccessToken(
allocator: std.mem.Allocator,
token_url: []const u8,
client_id: []const u8,
refresh_token: []const u8,
) !OAuthToken {
var client = try http_util.ProxyHttpClient.init(allocator);
defer client.deinit();
const payload = try std.fmt.allocPrint(
allocator,
"grant_type=refresh_token&refresh_token={s}&client_id={s}",
.{ refresh_token, client_id },
);
defer allocator.free(payload);
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
const result = try client.fetch(.{
.location = .{ .url = token_url },
.method = .POST,
.payload = payload,
.extra_headers = &.{
.{ .name = "Content-Type", .value = "application/x-www-form-urlencoded" },
.{ .name = "User-Agent", .value = "nullClaw/1.0" },
},
.response_writer = &aw.writer,
});
if (result.status != .ok) return error.TokenRefreshFailed;
const resp_body = aw.writer.buffer[0..aw.writer.end];
var token = try parseTokenResponse(allocator, resp_body);
// Preserve old refresh_token if response omits a new one
if (token.refresh_token == null) {
token.refresh_token = try allocator.dupe(u8, refresh_token);
}
return token;
}
// ── Credential Deletion ───────────────────────────────────────────────
/// Delete a credential for the given provider from auth.json in the config directory.
/// Returns true if the credential was found and removed.
pub fn deleteCredential(allocator: std.mem.Allocator, provider: []const u8) !bool {
const file_path = credentialFilePath(allocator) catch |err| switch (err) {
error.HomeDirNotFound => return error.HomeNotSet,
else => return err,
};
defer allocator.free(file_path);
var existing = loadAllCredentials(allocator, file_path) orelse return false;
defer {
var it = existing.iterator();
while (it.next()) |entry| {
allocator.free(entry.key_ptr.*);
freeStoredToken(allocator, entry.value_ptr.*);
}
existing.deinit();
}
// Check if provider exists
var found = false;
var remove_it = existing.iterator();
while (remove_it.next()) |entry| {
if (std.mem.eql(u8, entry.key_ptr.*, provider)) {
found = true;
break;
}
}
if (!found) return false;
// Remove and re-serialize
if (existing.fetchRemove(provider)) |old| {
allocator.free(old.key);
freeStoredToken(allocator, old.value);
}
var buf: std.ArrayListUnmanaged(u8) = .empty;
defer buf.deinit(allocator);
try buf.append(allocator, '{');
var first = true;
var iter = existing.iterator();
while (iter.next()) |entry| {
if (!first) try buf.append(allocator, ',');
first = false;
try json_util.appendJsonKey(&buf, allocator, entry.key_ptr.*);
try buf.append(allocator, '{');
try json_util.appendJsonKeyValue(&buf, allocator, "access_token", entry.value_ptr.*.access_token);
if (entry.value_ptr.*.refresh_token) |rt| {
try buf.append(allocator, ',');
try json_util.appendJsonKeyValue(&buf, allocator, "refresh_token", rt);
}
try buf.append(allocator, ',');
try json_util.appendJsonInt(&buf, allocator, "expires_at", entry.value_ptr.*.expires_at);
try buf.append(allocator, ',');
try json_util.appendJsonKeyValue(&buf, allocator, "token_type", entry.value_ptr.*.token_type);
try buf.append(allocator, '}');
}
try buf.append(allocator, '}');
try writeCredentialsFileAtomic(file_path, buf.items);
return true;
}
// ── Device Code Flow (RFC 8628) ────────────────────────────────────────
pub const DeviceCode = struct {
device_code: []const u8,
user_code: []const u8,
verification_uri: []const u8,
interval: u32,
expires_in: u32,
pub fn deinit(self: DeviceCode, allocator: std.mem.Allocator) void {
allocator.free(self.device_code);
allocator.free(self.user_code);
allocator.free(self.verification_uri);
}
};
/// Initiate a device code flow by POSTing to the device authorization URL.
pub fn startDeviceCodeFlow(
allocator: std.mem.Allocator,
client_id: []const u8,
device_auth_url: []const u8,
scope: []const u8,
) !DeviceCode {
var client = try http_util.ProxyHttpClient.init(allocator);
defer client.deinit();
const payload = try std.fmt.allocPrint(
allocator,
"client_id={s}&scope={s}",
.{ client_id, scope },
);
defer allocator.free(payload);
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
const result = try client.fetch(.{
.location = .{ .url = device_auth_url },
.method = .POST,
.payload = payload,
.extra_headers = &.{
.{ .name = "Content-Type", .value = "application/x-www-form-urlencoded" },
.{ .name = "User-Agent", .value = "nullClaw/1.0" },
},
.response_writer = &aw.writer,
});
if (result.status != .ok) return error.DeviceCodeRequestFailed;
const resp_body = aw.writer.buffer[0..aw.writer.end];
return parseDeviceCodeResponse(allocator, resp_body);
}
fn parseDeviceCodeResponse(allocator: std.mem.Allocator, body: []const u8) !DeviceCode {
const parsed = std.json.parseFromSlice(std.json.Value, allocator, body, .{}) catch
return error.DeviceCodeParseFailed;
defer parsed.deinit();
const obj = switch (parsed.value) {
.object => |o| o,
else => return error.DeviceCodeParseFailed,
};
const dc = switch (obj.get("device_code") orelse return error.DeviceCodeParseFailed) {
.string => |s| s,
else => return error.DeviceCodeParseFailed,
};
const uc = switch (obj.get("user_code") orelse return error.DeviceCodeParseFailed) {
.string => |s| s,
else => return error.DeviceCodeParseFailed,
};
const vu = switch (obj.get("verification_uri") orelse
obj.get("verification_url") orelse return error.DeviceCodeParseFailed) {
.string => |s| s,
else => return error.DeviceCodeParseFailed,
};
const interval: u32 = if (obj.get("interval")) |v| switch (v) {
.integer => |i| @intCast(i),
else => 5,
} else 5;
const expires_in: u32 = if (obj.get("expires_in")) |v| switch (v) {
.integer => |i| @intCast(i),
else => 900,
} else 900;
const dc_owned = try allocator.dupe(u8, dc);
errdefer allocator.free(dc_owned);
const uc_owned = try allocator.dupe(u8, uc);
errdefer allocator.free(uc_owned);
const vu_owned = try allocator.dupe(u8, vu);
return .{
.device_code = dc_owned,
.user_code = uc_owned,
.verification_uri = vu_owned,
.interval = interval,
.expires_in = expires_in,
};
}
/// Poll the token endpoint until the user authorizes the device.
/// Returns the OAuthToken on success or error on timeout / denied.
pub fn pollDeviceCode(
allocator: std.mem.Allocator,
token_url: []const u8,
client_id: []const u8,
device_code: []const u8,
interval_s: u32,
) !OAuthToken {
var client = try http_util.ProxyHttpClient.init(allocator);
defer client.deinit();
const payload = try std.fmt.allocPrint(
allocator,
"client_id={s}&device_code={s}&grant_type=urn:ietf:params:oauth:grant-type:device_code",
.{ client_id, device_code },
);
defer allocator.free(payload);
const interval_ns: u64 = @as(u64, interval_s) * std.time.ns_per_s;
const max_attempts: u32 = 120;
for (0..max_attempts) |_| {
std_compat.thread.sleep(interval_ns);
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
const result = client.fetch(.{
.location = .{ .url = token_url },
.method = .POST,
.payload = payload,
.extra_headers = &.{
.{ .name = "Content-Type", .value = "application/x-www-form-urlencoded" },
.{ .name = "User-Agent", .value = "nullClaw/1.0" },
},
.response_writer = &aw.writer,
}) catch continue;
const resp_body = aw.writer.buffer[0..aw.writer.end];
if (result.status == .ok) {
return parseTokenResponse(allocator, resp_body) catch continue;
}
// Check for terminal errors
const parsed = std.json.parseFromSlice(std.json.Value, allocator, resp_body, .{}) catch continue;
defer parsed.deinit();
const obj = switch (parsed.value) {
.object => |o| o,
else => continue,
};
const err_str = switch (obj.get("error") orelse continue) {
.string => |s| s,
else => continue,
};
if (std.mem.eql(u8, err_str, "authorization_pending") or
std.mem.eql(u8, err_str, "slow_down"))
{
continue;
}
// access_denied, expired_token, etc.
return error.DeviceCodeDenied;
}
return error.DeviceCodeTimeout;
}
fn parseTokenResponse(allocator: std.mem.Allocator, body: []const u8) !OAuthToken {
const parsed = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
defer parsed.deinit();
const obj = switch (parsed.value) {
.object => |o| o,
else => return error.TokenParseFailed,
};
const at = switch (obj.get("access_token") orelse return error.TokenParseFailed) {
.string => |s| s,
else => return error.TokenParseFailed,
};
const rt: ?[]const u8 = if (obj.get("refresh_token")) |v| switch (v) {
.string => |s| if (s.len > 0) s else null,
else => null,
} else null;
const expires_in: i64 = if (obj.get("expires_in")) |v| switch (v) {
.integer => |i| i,
.float => |f| @intFromFloat(f),
else => 3600,
} else 3600;
const tt: []const u8 = if (obj.get("token_type")) |v| switch (v) {
.string => |s| s,
else => "Bearer",
} else "Bearer";
const at_owned = try allocator.dupe(u8, at);
errdefer allocator.free(at_owned);
const rt_owned: ?[]const u8 = if (rt) |r| try allocator.dupe(u8, r) else null;
errdefer if (rt_owned) |r| allocator.free(r);
const tt_owned = try allocator.dupe(u8, tt);
return .{
.access_token = at_owned,
.refresh_token = rt_owned,
.expires_at = std_compat.time.timestamp() + expires_in,
.token_type = tt_owned,
};
}
// ════════════════════════════════════════════════════════════════════════
// Tests
// ════════════════════════════════════════════════════════════════════════
test "PKCE verifier length is 86 chars (64 bytes base64url no-pad)" {
const pkce = try generatePkce(std.testing.allocator);
defer pkce.deinit(std.testing.allocator);
// 64 bytes → base64url no-pad = ceil(64*4/3) = 86 chars
try std.testing.expectEqual(@as(usize, 86), pkce.verifier.len);
}
test "PKCE challenge is 43 chars (32 bytes SHA-256 base64url no-pad)" {
const pkce = try generatePkce(std.testing.allocator);
defer pkce.deinit(std.testing.allocator);
// SHA-256 = 32 bytes → base64url no-pad = ceil(32*4/3) = 43 chars
try std.testing.expectEqual(@as(usize, 43), pkce.challenge.len);
}
test "PKCE challenge is valid base64url" {
const pkce = try generatePkce(std.testing.allocator);
defer pkce.deinit(std.testing.allocator);
for (pkce.challenge) |c| {
try std.testing.expect(
(c >= 'A' and c <= 'Z') or
(c >= 'a' and c <= 'z') or
(c >= '0' and c <= '9') or
c == '-' or c == '_',
);
}
}
test "PKCE method is S256" {
const pkce = try generatePkce(std.testing.allocator);
defer pkce.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("S256", pkce.method);
}
test "PKCE challenge matches SHA-256 of verifier" {
const pkce = try generatePkce(std.testing.allocator);
defer pkce.deinit(std.testing.allocator);
var hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(pkce.verifier, &hash, .{});
const expected = try base64UrlEncodeAlloc(std.testing.allocator, &hash);
defer std.testing.allocator.free(expected);
try std.testing.expectEqualStrings(expected, pkce.challenge);
}
test "OAuthToken isExpired returns true for past expiry" {
const token = OAuthToken{
.access_token = "tok",
.expires_at = std_compat.time.timestamp() - 3600,
};
try std.testing.expect(token.isExpired());
}
test "OAuthToken isExpired returns false for far-future expiry" {
const token = OAuthToken{
.access_token = "tok",
.expires_at = std_compat.time.timestamp() + 3600,
};
try std.testing.expect(!token.isExpired());
}
test "OAuthToken isExpired returns false when expires_at is zero" {
const token = OAuthToken{
.access_token = "tok",
.expires_at = 0,
};
try std.testing.expect(!token.isExpired());
}
test "OAuthToken isExpired buffer: token expiring in 200s is expired" {
const token = OAuthToken{
.access_token = "tok",
.expires_at = std_compat.time.timestamp() + 200,
};
// 200s < 300s buffer → should be expired
try std.testing.expect(token.isExpired());
}
test "OAuthToken isExpired buffer: token expiring in 400s is NOT expired" {
const token = OAuthToken{
.access_token = "tok",
.expires_at = std_compat.time.timestamp() + 400,
};
// 400s > 300s buffer → not expired
try std.testing.expect(!token.isExpired());
}
test "parseDeviceCodeResponse parses valid response" {
const body =
\\{"device_code":"dev123","user_code":"ABCD-1234","verification_uri":"https://example.com/activate","interval":5,"expires_in":600}
;
const dc = try parseDeviceCodeResponse(std.testing.allocator, body);
defer dc.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("dev123", dc.device_code);
try std.testing.expectEqualStrings("ABCD-1234", dc.user_code);
try std.testing.expectEqualStrings("https://example.com/activate", dc.verification_uri);
try std.testing.expectEqual(@as(u32, 5), dc.interval);
try std.testing.expectEqual(@as(u32, 600), dc.expires_in);
}
test "parseDeviceCodeResponse handles verification_url alias" {
const body =
\\{"device_code":"dc","user_code":"UC","verification_url":"https://ex.com/v","interval":10,"expires_in":300}
;
const dc = try parseDeviceCodeResponse(std.testing.allocator, body);
defer dc.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("https://ex.com/v", dc.verification_uri);
}
test "parseDeviceCodeResponse defaults for missing interval/expires_in" {
const body =
\\{"device_code":"dc","user_code":"UC","verification_uri":"https://ex.com"}
;
const dc = try parseDeviceCodeResponse(std.testing.allocator, body);
defer dc.deinit(std.testing.allocator);
try std.testing.expectEqual(@as(u32, 5), dc.interval);
try std.testing.expectEqual(@as(u32, 900), dc.expires_in);
}
test "parseDeviceCodeResponse fails on missing device_code" {
const body =
\\{"user_code":"UC","verification_uri":"https://ex.com"}
;
try std.testing.expectError(error.DeviceCodeParseFailed, parseDeviceCodeResponse(std.testing.allocator, body));
}
test "parseTokenResponse parses valid token" {
const body =
\\{"access_token":"ya29.xyz","refresh_token":"1//abc","expires_in":3600,"token_type":"Bearer"}
;
const token = try parseTokenResponse(std.testing.allocator, body);
defer token.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("ya29.xyz", token.access_token);
try std.testing.expectEqualStrings("1//abc", token.refresh_token.?);
try std.testing.expect(token.expires_at > std_compat.time.timestamp());
}
test "parseTokenResponse fails on missing access_token" {
const body =
\\{"refresh_token":"rt","expires_in":3600}
;
try std.testing.expectError(error.TokenParseFailed, parseTokenResponse(std.testing.allocator, body));
}
test "base64UrlEncodeAlloc produces correct output" {
const input = "hello";
const encoded = try base64UrlEncodeAlloc(std.testing.allocator, input);
defer std.testing.allocator.free(encoded);
try std.testing.expectEqualStrings("aGVsbG8", encoded);
}
test "parseTokenResponse preserves refresh_token in refresh response" {
// Simulates a refresh response that includes a new refresh_token
const body =
\\{"access_token":"new_access","refresh_token":"new_refresh","expires_in":7200,"token_type":"Bearer"}
;
const token = try parseTokenResponse(std.testing.allocator, body);
defer token.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("new_access", token.access_token);
try std.testing.expectEqualStrings("new_refresh", token.refresh_token.?);
try std.testing.expectEqualStrings("Bearer", token.token_type);
try std.testing.expect(token.expires_at > std_compat.time.timestamp());
}
test "parseTokenResponse handles missing refresh_token in response" {
const body =
\\{"access_token":"refreshed_access","expires_in":3600,"token_type":"Bearer"}
;
const token = try parseTokenResponse(std.testing.allocator, body);
defer token.deinit(std.testing.allocator);
try std.testing.expectEqualStrings("refreshed_access", token.access_token);
try std.testing.expect(token.refresh_token == null);
}
test "Allocating writer deinit frees full buffer — no invalid free on sub-slice (issue #42)" {
const allocator = std.testing.allocator;
// Simulate the pattern from refreshAccessToken / pollDeviceCode:
// Io.Writer.Allocating grows geometrically, so capacity > written length.
// The old code did allocator.free(buffer[0..end]) — a sub-slice free
// that is UB (length mismatch). The fix uses aw.deinit() instead.
{
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try aw.writer.writeAll(
\\{"access_token":"test_tok","refresh_token":"test_rt","expires_in":7200,"token_type":"Bearer"}
);
// Confirm geometric growth: capacity > written
try std.testing.expect(aw.writer.buffer.len > aw.writer.end);
const resp_body = aw.writer.buffer[0..aw.writer.end];
const token = try parseTokenResponse(allocator, resp_body);
defer token.deinit(allocator);
try std.testing.expectEqualStrings("test_tok", token.access_token);
try std.testing.expectEqualStrings("test_rt", token.refresh_token.?);
try std.testing.expectEqualStrings("Bearer", token.token_type);
}
// Same pattern for parseDeviceCodeResponse (startDeviceCodeFlow path)
{
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try aw.writer.writeAll(
\\{"device_code":"dev123","user_code":"ABCD-1234","verification_uri":"https://example.com/verify","interval":5,"expires_in":900}
);
try std.testing.expect(aw.writer.buffer.len > aw.writer.end);
const resp_body = aw.writer.buffer[0..aw.writer.end];
const dc = try parseDeviceCodeResponse(allocator, resp_body);
defer dc.deinit(allocator);
try std.testing.expectEqualStrings("dev123", dc.device_code);
try std.testing.expectEqualStrings("ABCD-1234", dc.user_code);
try std.testing.expectEqualStrings("https://example.com/verify", dc.verification_uri);
try std.testing.expectEqual(@as(u32, 5), dc.interval);
}
// If we reach here without panic, DebugAllocator confirmed:
// 1. No invalid free (sub-slice length mismatch)
// 2. No memory leak (all allocations freed)
}
test "credentialFilePathFromConfigDir appends auth.json" {
const path = try credentialFilePathFromConfigDir(std.testing.allocator, "/tmp/nullclaw-home");
defer std.testing.allocator.free(path);
const expected = try std_compat.fs.path.join(std.testing.allocator, &.{ "/tmp/nullclaw-home", "auth.json" });
defer std.testing.allocator.free(expected);
try std.testing.expectEqualStrings(expected, path);
}
test "loadAllCredentials reads absolute auth path" {
var tmp_dir = std.testing.tmpDir(.{});
defer tmp_dir.cleanup();
const abs = try @import("compat").fs.Dir.wrap(tmp_dir.dir).realpathAlloc(std.testing.allocator, ".");
defer std.testing.allocator.free(abs);
const auth_path = try std_compat.fs.path.join(std.testing.allocator, &.{ abs, "auth.json" });
defer std.testing.allocator.free(auth_path);
const file = try fs_compat.createPath(auth_path, .{});
defer file.close();
try file.writeAll(
\\{"openai":{"access_token":"tok","expires_at":4102444800,"token_type":"Bearer"}}
);
var credentials = loadAllCredentials(std.testing.allocator, auth_path) orelse return error.TestUnexpectedResult;
defer {
var it = credentials.iterator();
while (it.next()) |entry| {
std.testing.allocator.free(entry.key_ptr.*);
freeStoredToken(std.testing.allocator, entry.value_ptr.*);
}
credentials.deinit();
}
const token = credentials.get("openai") orelse return error.TestUnexpectedResult;
try std.testing.expectEqualStrings("tok", token.access_token);
}