github-bot-sdk 0.2.1

A comprehensive Rust SDK for GitHub App integration with authentication, webhooks, and API client
Documentation
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
//! Tests for JWT generation functionality.

use super::*;
use chrono::{Duration, Utc};

// Test private key (2048-bit RSA key for testing only - DO NOT USE IN PRODUCTION)
// Generated with: open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y53SxOpS0cwlO7eqcdpyiD92/T3c2D
0VsR15UjGh49vQq6gNbx93IM/0ZTzZeDwSDJRJMCgYEAt2rIJpfGyp+zftUlAphY
XqToxELZG8l8pQWyH1WT4JkextGMYIvW/Ok59YHlqEr3ZkiCqOAdY8JgcRkfUKpw
ijSjPh7nCB1RD+2CKg8BEItmJMxTMy6K6N+qDptqKqVBAwBku2I389a5UOOu92Sq
JIygWv7ohRhhieEtT94TmikCgYEAxpomkJtB2qpB6XQSKEbi3JZHnjTz6b/nXRtI
l3YRLMzviSsjFyQOJgEFVHrFZQh+4nsK8WPC41V4qYrofiybQCQL9sTtgxg4/Cho
szz68OTOp+10pNPxHwbF55olHUKsURbBvq56DcRNkREttlEZOio1OAhvTKLWmlDD
8wz4py0CgYEAtFFj1yy5+sMFltznnbTQRQSHL1RPBW+DDl8L8N4iYNpn2jXdXzHZ
cacKwSEhb/Jfk1hWtMhMz6Rqay+J6L7p0M72+u5B9elsVLw2LxvKNTw4A+Ud5/y+
8psOAgF5tfAPoxS+guVqadLGbnj94dqr5jKl1cZ2q9lovcI1o5SeQpw=
-----END RSA PRIVATE KEY-----"#;

const TEST_PRIVATE_KEY_INVALID: &str = r#"-----BEGIN RSA PRIVATE KEY-----
INVALID KEY DATA HERE
-----END RSA PRIVATE KEY-----"#;

/// Helper to create a test private key.
fn test_private_key() -> PrivateKey {
    PrivateKey::from_pem(TEST_PRIVATE_KEY_PEM).expect("Test key should be valid")
}

mod jwt_generator_tests {
    use super::*;

    /// Assertion 1: JWT Token Generation
    ///
    /// Given: A valid GitHub App ID and private key
    /// When: generate_jwt() is called
    /// Then: Operation returns Ok(JwtToken) with valid JWT
    /// And: Token expires within 10 minutes (GitHub requirement)
    /// And: Token contains correct iss claim matching App ID
    #[tokio::test]
    async fn test_generate_jwt_with_valid_credentials() {
        let app_id = GitHubAppId::new(123456);
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        let result = generator.generate_jwt(app_id).await;

        assert!(result.is_ok(), "JWT generation should succeed");
        let jwt = result.unwrap();

        // Verify token is not expired
        assert!(!jwt.is_expired(), "JWT should not be immediately expired");

        // Verify app ID matches
        assert_eq!(jwt.app_id(), app_id, "JWT app_id should match input");

        // Verify expiration is within 10 minutes
        let time_until_expiry = jwt.time_until_expiry();
        assert!(
            time_until_expiry <= Duration::minutes(10),
            "JWT expiration should not exceed 10 minutes (GitHub requirement)"
        );
        assert!(
            time_until_expiry > Duration::minutes(0),
            "JWT should have positive time until expiry"
        );
    }

    /// Verify JWT structure is valid (header.payload.signature).
    #[tokio::test]
    async fn test_jwt_has_valid_structure() {
        let app_id = GitHubAppId::new(789);
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        let jwt = generator.generate_jwt(app_id).await.unwrap();
        let token_str = jwt.token();

        // JWT should have three parts separated by dots
        let parts: Vec<&str> = token_str.split('.').collect();
        assert_eq!(
            parts.len(),
            3,
            "JWT should have exactly 3 parts (header.payload.signature)"
        );

        // Each part should be non-empty
        assert!(!parts[0].is_empty(), "JWT header should not be empty");
        assert!(!parts[1].is_empty(), "JWT payload should not be empty");
        assert!(!parts[2].is_empty(), "JWT signature should not be empty");
    }

    /// Verify iat (issued at) claim is current timestamp (±5 seconds).
    #[tokio::test]
    async fn test_jwt_issued_at_is_current() {
        let app_id = GitHubAppId::new(555);
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        let before = Utc::now();
        let jwt = generator.generate_jwt(app_id).await.unwrap();
        let after = Utc::now();

        let issued_at = jwt.issued_at();

        // Issued at should be between before and after (with small margin)
        assert!(
            issued_at >= before - Duration::seconds(5),
            "JWT issued_at should be recent"
        );
        assert!(
            issued_at <= after + Duration::seconds(5),
            "JWT issued_at should not be in the future"
        );
    }

    /// Verify exp claim is iat + duration (max 10 minutes).
    #[tokio::test]
    async fn test_jwt_expiration_matches_duration() {
        let app_id = GitHubAppId::new(999);
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        let jwt = generator.generate_jwt(app_id).await.unwrap();

        let expected_expiry = jwt.issued_at() + generator.expiration_duration();
        let actual_expiry = jwt.expires_at();

        // Expiration should match issued_at + duration (with 1 second tolerance)
        let diff = (actual_expiry - expected_expiry).num_seconds().abs();
        assert!(
            diff <= 1,
            "JWT expiration should be issued_at + duration (tolerance: 1s)"
        );
    }

    /// Test custom expiration duration (8 minutes).
    #[tokio::test]
    async fn test_jwt_with_custom_expiration() {
        let app_id = GitHubAppId::new(111);
        let private_key = test_private_key();
        let custom_duration = Duration::minutes(8);
        let generator = RS256JwtGenerator::with_expiration(private_key, custom_duration);

        let jwt = generator.generate_jwt(app_id).await.unwrap();
        let time_until_expiry = jwt.time_until_expiry();

        // Should be approximately 8 minutes (with small tolerance)
        assert!(
            time_until_expiry <= Duration::minutes(8) + Duration::seconds(5),
            "JWT should expire in approximately 8 minutes"
        );
        assert!(
            time_until_expiry >= Duration::minutes(8) - Duration::seconds(5),
            "JWT expiration should match custom duration"
        );
    }

    /// Test that generator enforces 10-minute maximum.
    #[tokio::test]
    #[should_panic(expected = "JWT expiration cannot exceed 10 minutes")]
    async fn test_jwt_rejects_expiration_over_10_minutes() {
        let private_key = test_private_key();
        let _ = RS256JwtGenerator::with_expiration(private_key, Duration::minutes(11));
    }

    /// Test that multiple JWT generations produce different tokens.
    #[tokio::test]
    async fn test_multiple_jwt_generations_are_unique() {
        let app_id = GitHubAppId::new(222);
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        let jwt1 = generator.generate_jwt(app_id).await.unwrap();

        // Small delay to ensure different iat timestamp
        tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;

        let jwt2 = generator.generate_jwt(app_id).await.unwrap();

        // Tokens should be different (different iat timestamps)
        assert_ne!(
            jwt1.token(),
            jwt2.token(),
            "Successive JWT generations should produce different tokens"
        );
    }

    /// Test JWT generation with different app IDs.
    #[tokio::test]
    async fn test_jwt_generation_with_different_app_ids() {
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        let app_id_1 = GitHubAppId::new(111);
        let app_id_2 = GitHubAppId::new(222);

        let jwt1 = generator.generate_jwt(app_id_1).await.unwrap();
        let jwt2 = generator.generate_jwt(app_id_2).await.unwrap();

        // Verify correct app IDs
        assert_eq!(jwt1.app_id(), app_id_1);
        assert_eq!(jwt2.app_id(), app_id_2);

        // Tokens should be different
        assert_ne!(jwt1.token(), jwt2.token());
    }
}

mod private_key_tests {
    use super::*;

    /// Assertion 2: JWT Token with Invalid Private Key
    ///
    /// Given: A GitHub App ID and malformed private key
    /// When: JWT generation is attempted
    /// Then: Operation returns Err(AuthenticationError::InvalidPrivateKey)
    /// And: No token is generated
    /// And: Error message does not expose private key content
    #[tokio::test]
    async fn test_generate_jwt_with_invalid_private_key() {
        let result = PrivateKey::from_pem(TEST_PRIVATE_KEY_INVALID);

        assert!(
            result.is_err(),
            "Invalid private key should be rejected during parsing"
        );

        let err = result.unwrap_err();
        let err_msg = format!("{:?}", err);

        // Error message should not contain key material
        assert!(
            !err_msg.contains("INVALID KEY DATA"),
            "Error message should not expose key content"
        );
    }

    /// Test valid PEM key loading.
    #[test]
    fn test_private_key_from_valid_pem() {
        let result = PrivateKey::from_pem(TEST_PRIVATE_KEY_PEM);

        assert!(result.is_ok(), "Valid PEM key should load successfully");
    }

    /// Test PEM key with wrong format.
    #[test]
    fn test_private_key_from_malformed_pem() {
        let malformed_pem = "NOT A VALID PEM KEY";
        let result = PrivateKey::from_pem(malformed_pem);

        assert!(result.is_err(), "Malformed PEM should be rejected");
    }

    /// Test empty PEM key.
    #[test]
    fn test_private_key_from_empty_pem() {
        let empty_pem = "";
        let result = PrivateKey::from_pem(empty_pem);

        assert!(result.is_err(), "Empty PEM should be rejected");
    }

    /// Test PEM key with extra whitespace.
    #[test]
    fn test_private_key_from_pem_with_whitespace() {
        let pem_with_whitespace = format!("\n\n{}\n\n", TEST_PRIVATE_KEY_PEM);
        let result = PrivateKey::from_pem(&pem_with_whitespace);

        // Should handle extra whitespace gracefully
        assert!(result.is_ok(), "PEM parser should handle extra whitespace");
    }

    /// Verify that PrivateKey doesn't expose key data in Debug output.
    #[test]
    fn test_private_key_debug_redaction() {
        let key = test_private_key();
        let debug_output = format!("{:?}", key);

        // Debug output should not contain actual key data
        assert!(
            !debug_output.contains("MIIEpAIBAAKCAQEA"),
            "Debug output should not expose key material"
        );
        assert!(
            debug_output.contains("<REDACTED>") || debug_output.contains("PrivateKey"),
            "Debug output should indicate redaction or type"
        );
    }
}

mod jwt_claims_tests {
    use super::*;

    /// Test JWT claims structure.
    #[test]
    fn test_jwt_claims_construction() {
        let app_id = GitHubAppId::new(12345);
        let now = Utc::now();
        let iat = now.timestamp();
        let exp = (now + Duration::minutes(10)).timestamp();

        let claims = JwtClaims {
            iss: app_id,
            iat,
            exp,
        };

        assert_eq!(claims.iss, app_id);
        assert_eq!(claims.iat, iat);
        assert_eq!(claims.exp, exp);
    }

    /// Test JWT claims serialization.
    #[test]
    fn test_jwt_claims_serialization() {
        let app_id = GitHubAppId::new(67890);
        let now = Utc::now();
        let claims = JwtClaims {
            iss: app_id,
            iat: now.timestamp(),
            exp: (now + Duration::minutes(10)).timestamp(),
        };

        let json = serde_json::to_string(&claims);
        assert!(json.is_ok(), "JWT claims should serialize to JSON");

        let json_str = json.unwrap();
        assert!(json_str.contains("\"iss\""));
        assert!(json_str.contains("\"iat\""));
        assert!(json_str.contains("\"exp\""));
    }
}

mod expiration_tests {
    use super::*;

    /// Test JWT expires_soon detection.
    #[tokio::test]
    async fn test_jwt_expires_soon_detection() {
        let app_id = GitHubAppId::new(333);
        let private_key = test_private_key();

        // Create generator with 2-minute expiration for testing
        let generator = RS256JwtGenerator::with_expiration(private_key, Duration::minutes(2));

        let jwt = generator.generate_jwt(app_id).await.unwrap();

        // Should not expire soon with 30-second margin (1 min 30 sec remaining)
        assert!(
            !jwt.expires_soon(Duration::seconds(30)),
            "JWT should not expire soon with small margin (30s)"
        );

        // Should expire soon with 3-minute margin (token only lasts 2 minutes)
        assert!(
            jwt.expires_soon(Duration::minutes(3)),
            "JWT should expire soon with large margin (3 min)"
        );
    }

    /// Test time_until_expiry is accurate.
    #[tokio::test]
    async fn test_jwt_time_until_expiry() {
        let app_id = GitHubAppId::new(444);
        let private_key = test_private_key();
        let duration = Duration::minutes(5);
        let generator = RS256JwtGenerator::with_expiration(private_key, duration);

        let jwt = generator.generate_jwt(app_id).await.unwrap();
        let time_remaining = jwt.time_until_expiry();

        // Should be approximately 5 minutes (with tolerance for execution time)
        assert!(
            time_remaining <= Duration::minutes(5),
            "Time until expiry should not exceed configured duration"
        );
        assert!(
            time_remaining >= Duration::minutes(4) + Duration::seconds(55),
            "Time until expiry should be close to configured duration"
        );
    }
}

mod trait_implementation_tests {
    use super::*;

    /// Test that JwtGenerator trait is object-safe (can be used as dyn trait).
    #[tokio::test]
    async fn test_jwt_generator_trait_object() {
        let app_id = GitHubAppId::new(555);
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        // Use as trait object
        let trait_obj: &dyn JwtGenerator = &generator;
        let jwt = trait_obj.generate_jwt(app_id).await.unwrap();

        assert_eq!(jwt.app_id(), app_id);
    }

    /// Test expiration_duration accessor.
    #[test]
    fn test_jwt_generator_expiration_duration() {
        let private_key = test_private_key();
        let generator = RS256JwtGenerator::new(private_key);

        assert_eq!(
            generator.expiration_duration(),
            Duration::minutes(10),
            "Default expiration should be 10 minutes"
        );
    }

    /// Test custom expiration_duration accessor.
    #[test]
    fn test_jwt_generator_custom_expiration_duration() {
        let private_key = test_private_key();
        let custom_duration = Duration::minutes(7);
        let generator = RS256JwtGenerator::with_expiration(private_key, custom_duration);

        assert_eq!(
            generator.expiration_duration(),
            custom_duration,
            "Custom expiration should be accessible"
        );
    }
}