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
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
//! GitHub App authentication types and interfaces.
//!
//! This module provides the authentication foundation for GitHub Apps, handling the complexities
//! of GitHub's two-tier authentication model with type safety and production-ready patterns.
//!
//! # Overview
//!
//! GitHub Apps use a two-tier authentication system:
//!
//! 1. **App-level JWT tokens** - Short-lived (max 10 minutes) tokens for app-level operations
//! 2. **Installation tokens** - Scoped tokens for operations within specific installations
//!
//! This module provides:
//!
//! - **ID Types** - Branded types for [`GitHubAppId`], [`InstallationId`], [`RepositoryId`], [`UserId`]
//! - **Token Types** - [`JsonWebToken`] and [`InstallationToken`] with automatic expiration tracking
//! - **Permission Models** - [`InstallationPermissions`] and [`PermissionLevel`] for access control
//! - **Trait Interfaces** - [`AuthenticationProvider`], [`SecretProvider`], [`TokenCache`], [`JwtSigner`]
//! - **Metadata Types** - [`Installation`], [`Repository`], [`User`] for GitHub entities
//!
//! # Authentication Flow
//!
//! ```text
//! ┌─────────────────┐
//! │  GitHub App ID  │
//! │  + Private Key  │
//! └────────┬────────┘
//!//!//! ┌─────────────────┐
//! │   JWT Token     │  ◄── Sign with RS256 (max 10 min expiry)
//! │ (App-level)     │
//! └────────┬────────┘
//!//!//! ┌─────────────────┐
//! │  Installation   │  ◄── Exchange JWT for installation token
//! │     Token       │      (scoped to installation permissions)
//! └─────────────────┘
//! ```
//!
//! # Usage Examples
//!
//! ## Working with ID Types
//!
//! ID types use the newtype pattern to prevent mixing up different identifier types:
//!
//! ```
//! use github_bot_sdk::auth::{GitHubAppId, InstallationId, RepositoryId};
//!
//! // Create IDs - type-safe, cannot be confused
//! let app_id = GitHubAppId::new(123456);
//! let installation_id = InstallationId::new(789012);
//! let repo_id = RepositoryId::new(345678);
//!
//! // Parse from strings
//! let app_id: GitHubAppId = "123456".parse().unwrap();
//! assert_eq!(app_id.as_u64(), 123456);
//!
//! // Convert to strings for display
//! println!("App ID: {}", app_id);  // Prints: App ID: 123456
//! ```
//!
//! ## Token Expiration Checking
//!
//! Tokens automatically track expiration and provide methods to check validity:
//!
//! ```
//! use github_bot_sdk::auth::{JsonWebToken, GitHubAppId};
//! use chrono::{Utc, Duration};
//!
//! let app_id = GitHubAppId::new(123);
//! let expires_at = Utc::now() + Duration::minutes(10);
//! let jwt = JsonWebToken::new("eyJhbGc...".to_string(), app_id, expires_at);
//!
//! // Check if token is expired
//! if jwt.is_expired() {
//!     println!("Token has expired - need to generate new one");
//! }
//!
//! // Check if token expires soon (within specified duration)
//! if jwt.expires_soon(Duration::minutes(5)) {
//!     println!("Token expires in less than 5 minutes - should refresh proactively");
//! }
//! ```
//!
//! ## Implementing Authentication Provider
//!
//! The [`AuthenticationProvider`] trait is the main interface for authentication:
//!
//! ```no_run
//! use github_bot_sdk::auth::{
//!     AuthenticationProvider, GitHubAppId, InstallationId,
//!     JsonWebToken, InstallationToken, Installation, Repository
//! };
//! use github_bot_sdk::error::AuthError;
//! use async_trait::async_trait;
//!
//! struct MyAuthProvider {
//!     // Your implementation fields
//! }
//!
//! #[async_trait]
//! impl AuthenticationProvider for MyAuthProvider {
//!     async fn app_token(&self) -> Result<JsonWebToken, AuthError> {
//!         // Generate JWT for app-level operations
//!         // - Read private key from secure storage
//!         // - Sign JWT claims with RS256
//!         // - Set 10-minute expiration
//!         # todo!()
//!     }
//!
//!     async fn installation_token(
//!         &self,
//!         installation_id: InstallationId,
//!     ) -> Result<InstallationToken, AuthError> {
//!         // Get installation token
//!         // - Generate app JWT
//!         // - Exchange for installation token via GitHub API
//!         // - Cache token until near expiration
//!         # todo!()
//!     }
//!
//!     async fn refresh_installation_token(
//!         &self,
//!         installation_id: InstallationId,
//!     ) -> Result<InstallationToken, AuthError> {
//!         // Force refresh - bypass cache
//!         # todo!()
//!     }
//!
//!     async fn list_installations(&self) -> Result<Vec<Installation>, AuthError> {
//!         // List all installations for this app
//!         # todo!()
//!     }
//!
//!     async fn get_installation_repositories(
//!         &self,
//!         installation_id: InstallationId,
//!     ) -> Result<Vec<Repository>, AuthError> {
//!         // Get repositories accessible to installation
//!         # todo!()
//!     }
//! }
//! ```
//!
//! ## Working with Permissions
//!
//! Installation tokens include permission information:
//!
//! ```
//! use github_bot_sdk::auth::{InstallationPermissions, PermissionLevel};
//!
//! // Create permissions with struct fields (not HashMap)
//! let mut permissions = InstallationPermissions {
//!     issues: PermissionLevel::Write,
//!     pull_requests: PermissionLevel::Write,
//!     contents: PermissionLevel::Write,
//!     metadata: PermissionLevel::Read,
//!     checks: PermissionLevel::None,
//!     actions: PermissionLevel::None,
//! };
//!
//! // Check permissions via fields
//! match permissions.contents {
//!     PermissionLevel::Read => println!("Read-only access to contents"),
//!     PermissionLevel::Write => println!("Read-write access to contents"),
//!     PermissionLevel::Admin => println!("Admin access to contents"),
//!     PermissionLevel::None => println!("No access to contents"),
//! }
//! ```
//!
//! ## Secret Management
//!
//! Implement [`SecretProvider`] to integrate with your secret management system:
//!
//! ```no_run
//! use github_bot_sdk::auth::{SecretProvider, PrivateKey, GitHubAppId};
//! use github_bot_sdk::error::SecretError;
//! use chrono::Duration;
//! use async_trait::async_trait;
//!
//! struct MySecretProvider {
//!     // Your secret storage integration
//! }
//!
//! #[async_trait]
//! impl SecretProvider for MySecretProvider {
//!     async fn get_private_key(&self) -> Result<PrivateKey, SecretError> {
//!         // Retrieve private key from Azure Key Vault, AWS Secrets Manager,
//!         // environment variables, or your preferred secret store
//!         # todo!()
//!     }
//!
//!     async fn get_app_id(&self) -> Result<GitHubAppId, SecretError> {
//!         // Retrieve GitHub App ID
//!         # todo!()
//!     }
//!
//!     async fn get_webhook_secret(&self) -> Result<String, SecretError> {
//!         // Retrieve webhook secret for signature validation
//!         # todo!()
//!     }
//!
//!     fn cache_duration(&self) -> Duration {
//!         // How long to cache secrets (e.g., 1 hour)
//!         Duration::hours(1)
//!     }
//! }
//! ```
//!
//! # Security Considerations
//!
//! This module implements several security best practices:
//!
//! - **Memory Safety** - Token types implement `Drop` to zero memory
//! - **No Logging** - Debug implementations redact sensitive values
//! - **Type Safety** - Branded types prevent ID confusion at compile time
//! - **Expiration Tracking** - Automatic token expiration detection
//! - **Constant-Time Comparison** - Used where timing attacks are a concern
//!
//! # Error Handling
//!
//! Authentication operations can fail for various reasons:
//!
//! - [`AuthError::InvalidCredentials`] - Invalid private key or app ID
//! - [`AuthError::TokenExpired`] - Token has expired and needs refresh
//! - [`AuthError::InsufficientPermissions`] - Insufficient permissions for operation
//! - [`AuthError::GitHubApiError`] - GitHub API errors including rate limiting
//! - [`AuthError::NetworkError`] - Network connectivity issues
//!
//! All errors include context for debugging and support retry classification.
//!
//! # Architecture
//!
//! This module follows the ports and adapters (hexagonal) architecture:
//!
//! - **Domain Types** - ID types, token types, permission models (in this module)
//! - **Port Interfaces** - Traits for external dependencies ([`SecretProvider`], [`TokenCache`], etc.)
//! - **Adapters** - Your implementations for specific infrastructure (Azure, AWS, etc.)
//!
//! This design enables:
//! - Testability through dependency injection
//! - Flexibility to swap infrastructure components
//! - Clear separation between domain logic and infrastructure
//!
//! # See Also
//!
//! - [`crate::client`] - GitHub API client using these authentication types
//! - [`crate::webhook`] - Webhook signature validation using secrets from this module
//! - [GitHub App Authentication Documentation](https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps)

use chrono::{DateTime, Duration, Utc};
use serde::{Deserialize, Serialize};
use std::str::FromStr;

use crate::error::{ApiError, AuthError, CacheError, SecretError, SigningError, ValidationError};

// ============================================================================
// Core ID Types
// ============================================================================

/// GitHub App identifier assigned during app registration.
///
/// This is a globally unique identifier for your GitHub App, found in the
/// app settings page. It's used for JWT generation and app identification.
///
/// # Examples
///
/// ```
/// use github_bot_sdk::auth::GitHubAppId;
///
/// let app_id = GitHubAppId::new(123456);
/// assert_eq!(app_id.as_u64(), 123456);
/// assert_eq!(app_id.to_string(), "123456");
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct GitHubAppId(u64);

impl GitHubAppId {
    /// Create a new GitHub App ID.
    ///
    /// # Examples
    ///
    /// ```
    /// use github_bot_sdk::auth::GitHubAppId;
    ///
    /// let app_id = GitHubAppId::new(123456);
    /// ```
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the raw u64 value.
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for GitHubAppId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for GitHubAppId {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let id = s
            .parse::<u64>()
            .map_err(|_| ValidationError::InvalidFormat {
                field: "github_app_id".to_string(),
                message: "must be a positive integer".to_string(),
            })?;
        Ok(Self::new(id))
    }
}

/// GitHub App installation identifier for specific accounts.
///
/// When a GitHub App is installed on an organization or user account, GitHub
/// assigns an installation ID. This ID is used to obtain installation tokens
/// and perform operations on behalf of that installation.
///
/// # Examples
///
/// ```
/// use github_bot_sdk::auth::InstallationId;
///
/// let installation = InstallationId::new(98765);
/// assert_eq!(installation.as_u64(), 98765);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct InstallationId(u64);

impl InstallationId {
    /// Create a new installation ID.
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the raw u64 value.
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for InstallationId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for InstallationId {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let id = s
            .parse::<u64>()
            .map_err(|_| ValidationError::InvalidFormat {
                field: "installation_id".to_string(),
                message: "must be a positive integer".to_string(),
            })?;
        Ok(Self::new(id))
    }
}

/// Repository identifier used by GitHub API.
///
/// This numeric ID uniquely identifies a repository and remains stable even
/// if the repository is renamed or transferred.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct RepositoryId(u64);

impl RepositoryId {
    /// Create a new repository ID.
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the raw u64 value.
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for RepositoryId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for RepositoryId {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let id = s
            .parse::<u64>()
            .map_err(|_| ValidationError::InvalidFormat {
                field: "repository_id".to_string(),
                message: "must be a positive integer".to_string(),
            })?;
        Ok(Self::new(id))
    }
}

/// User identifier used by GitHub API.
///
/// This numeric ID uniquely identifies a user or organization and remains
/// stable even if the username changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct UserId(u64);

impl UserId {
    /// Create a new user ID.
    pub fn new(id: u64) -> Self {
        Self(id)
    }

    /// Get the raw u64 value.
    pub fn as_u64(&self) -> u64 {
        self.0
    }
}

impl std::fmt::Display for UserId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl FromStr for UserId {
    type Err = ValidationError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let id = s
            .parse::<u64>()
            .map_err(|_| ValidationError::InvalidFormat {
                field: "user_id".to_string(),
                message: "must be a positive integer".to_string(),
            })?;
        Ok(Self::new(id))
    }
}

// ============================================================================
// Token Types
// ============================================================================

/// JWT token for GitHub App authentication.
///
/// JSON Web Tokens (JWTs) are used to authenticate as a GitHub App. They have
/// a maximum lifetime of 10 minutes and are used to obtain installation tokens.
///
/// The token string is never exposed in Debug output for security.
///
/// # Examples
///
/// ```
/// use github_bot_sdk::auth::{JsonWebToken, GitHubAppId};
/// use chrono::{Utc, Duration};
///
/// let app_id = GitHubAppId::new(123);
/// let expires_at = Utc::now() + Duration::minutes(10);
/// let jwt = JsonWebToken::new("encoded.jwt.token".to_string(), app_id, expires_at);
///
/// assert!(!jwt.is_expired());
/// assert_eq!(jwt.app_id(), app_id);
/// ```
#[derive(Clone)]
pub struct JsonWebToken {
    token: String,
    issued_at: DateTime<Utc>,
    expires_at: DateTime<Utc>,
    app_id: GitHubAppId,
}

impl JsonWebToken {
    /// Create a new JWT token.
    ///
    /// # Arguments
    ///
    /// * `token` - The encoded JWT string
    /// * `app_id` - The GitHub App ID this token represents
    /// * `expires_at` - When the token expires (max 10 minutes from creation)
    pub fn new(token: String, app_id: GitHubAppId, expires_at: DateTime<Utc>) -> Self {
        let issued_at = Utc::now();
        Self {
            token,
            issued_at,
            expires_at,
            app_id,
        }
    }

    /// Get the token string for use in API requests.
    ///
    /// This should be included in the Authorization header as:
    /// `Authorization: Bearer <token>`
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Get the GitHub App ID this token represents.
    pub fn app_id(&self) -> GitHubAppId {
        self.app_id
    }

    /// Get when this token was issued.
    pub fn issued_at(&self) -> DateTime<Utc> {
        self.issued_at
    }

    /// Get when this token expires.
    pub fn expires_at(&self) -> DateTime<Utc> {
        self.expires_at
    }

    /// Check if the token is currently expired.
    pub fn is_expired(&self) -> bool {
        Utc::now() >= self.expires_at
    }

    /// Check if the token will expire soon.
    ///
    /// # Arguments
    ///
    /// * `margin` - How far in the future to check (e.g., 5 minutes)
    ///
    /// Returns true if the token will expire within the margin period.
    pub fn expires_soon(&self, margin: Duration) -> bool {
        Utc::now() + margin >= self.expires_at
    }

    /// Get the time remaining until expiry.
    pub fn time_until_expiry(&self) -> Duration {
        self.expires_at - Utc::now()
    }
}

// Security: Don't expose token in debug output
impl std::fmt::Debug for JsonWebToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("JsonWebToken")
            .field("app_id", &self.app_id)
            .field("issued_at", &self.issued_at)
            .field("expires_at", &self.expires_at)
            .field("token", &"<REDACTED>")
            .finish()
    }
}

/// Installation-scoped access token for GitHub API operations.
///
/// Installation tokens provide access to perform operations on behalf of a
/// specific installation. They have a 1-hour lifetime and include permission
/// and repository scope information.
///
/// The token string is never exposed in Debug output for security.
///
/// # Examples
///
/// ```
/// use github_bot_sdk::auth::{InstallationToken, InstallationId, InstallationPermissions, Permission, RepositoryId};
/// use chrono::{Utc, Duration};
///
/// let installation_id = InstallationId::new(456);
/// let expires_at = Utc::now() + Duration::hours(1);
/// let permissions = InstallationPermissions::default();
/// let repositories = vec![RepositoryId::new(789)];
///
/// let token = InstallationToken::new(
///     "ghs_token".to_string(),
///     installation_id,
///     expires_at,
///     permissions,
///     repositories,
/// );
///
/// assert_eq!(token.installation_id(), installation_id);
/// assert!(!token.is_expired());
/// ```
#[derive(Clone)]
pub struct InstallationToken {
    token: String,
    installation_id: InstallationId,
    issued_at: DateTime<Utc>,
    expires_at: DateTime<Utc>,
    permissions: InstallationPermissions,
    repositories: Vec<RepositoryId>,
}

impl InstallationToken {
    /// Create a new installation token.
    ///
    /// # Arguments
    ///
    /// * `token` - The token string from GitHub API
    /// * `installation_id` - The installation this token is for
    /// * `expires_at` - When the token expires (typically 1 hour)
    /// * `permissions` - The permissions granted to this token
    /// * `repositories` - The repositories this token can access
    pub fn new(
        token: String,
        installation_id: InstallationId,
        expires_at: DateTime<Utc>,
        permissions: InstallationPermissions,
        repositories: Vec<RepositoryId>,
    ) -> Self {
        let issued_at = Utc::now();
        Self {
            token,
            installation_id,
            issued_at,
            expires_at,
            permissions,
            repositories,
        }
    }

    /// Get the token string for use in API requests.
    ///
    /// This should be included in the Authorization header as:
    /// `Authorization: Bearer <token>`
    pub fn token(&self) -> &str {
        &self.token
    }

    /// Get the installation ID this token is for.
    pub fn installation_id(&self) -> InstallationId {
        self.installation_id
    }

    /// Get when this token was issued.
    pub fn issued_at(&self) -> DateTime<Utc> {
        self.issued_at
    }

    /// Get when this token expires.
    pub fn expires_at(&self) -> DateTime<Utc> {
        self.expires_at
    }

    /// Get the permissions granted to this token.
    pub fn permissions(&self) -> &InstallationPermissions {
        &self.permissions
    }

    /// Get the repositories this token can access.
    pub fn repositories(&self) -> &[RepositoryId] {
        &self.repositories
    }

    /// Check if the token is currently expired.
    pub fn is_expired(&self) -> bool {
        Utc::now() >= self.expires_at
    }

    /// Check if the token will expire soon.
    ///
    /// # Arguments
    ///
    /// * `margin` - How far in the future to check (e.g., 5 minutes)
    ///
    /// Returns true if the token will expire within the margin period.
    pub fn expires_soon(&self, margin: Duration) -> bool {
        Utc::now() + margin >= self.expires_at
    }

    /// Check if the token has a specific permission.
    ///
    /// # Examples
    ///
    /// ```
    /// # use github_bot_sdk::auth::{InstallationToken, InstallationId, InstallationPermissions, Permission, PermissionLevel, RepositoryId};
    /// # use chrono::{Utc, Duration};
    /// let mut permissions = InstallationPermissions::default();
    /// permissions.issues = PermissionLevel::Write;
    ///
    /// let token = InstallationToken::new(
    ///     "token".to_string(),
    ///     InstallationId::new(1),
    ///     Utc::now() + Duration::hours(1),
    ///     permissions,
    ///     vec![],
    /// );
    ///
    /// assert!(token.has_permission(Permission::ReadIssues));
    /// assert!(token.has_permission(Permission::WriteIssues));
    /// assert!(!token.has_permission(Permission::WriteContents));
    /// ```
    pub fn has_permission(&self, permission: Permission) -> bool {
        match permission {
            Permission::ReadIssues => matches!(
                self.permissions.issues,
                PermissionLevel::Read | PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::WriteIssues => matches!(
                self.permissions.issues,
                PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::ReadPullRequests => matches!(
                self.permissions.pull_requests,
                PermissionLevel::Read | PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::WritePullRequests => matches!(
                self.permissions.pull_requests,
                PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::ReadContents => matches!(
                self.permissions.contents,
                PermissionLevel::Read | PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::WriteContents => matches!(
                self.permissions.contents,
                PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::ReadChecks => matches!(
                self.permissions.checks,
                PermissionLevel::Read | PermissionLevel::Write | PermissionLevel::Admin
            ),
            Permission::WriteChecks => matches!(
                self.permissions.checks,
                PermissionLevel::Write | PermissionLevel::Admin
            ),
        }
    }

    /// Check if the token can access a specific repository.
    pub fn can_access_repository(&self, repo_id: RepositoryId) -> bool {
        self.repositories.contains(&repo_id)
    }
}

// Security: Redact token in debug output
impl std::fmt::Debug for InstallationToken {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("InstallationToken")
            .field("installation_id", &self.installation_id)
            .field("issued_at", &self.issued_at)
            .field("expires_at", &self.expires_at)
            .field("permissions", &self.permissions)
            .field("repositories", &self.repositories)
            .field("token", &"<REDACTED>")
            .finish()
    }
}

// ============================================================================
// Permission Types
// ============================================================================

/// Permissions granted to a GitHub App installation.
///
/// Each permission can be set to None, Read, Write, or Admin level.
/// See GitHub's documentation for details on what each permission allows.
///
/// # GitHub API Compatibility
///
/// The GitHub API returns permissions as optional fields - installations only
/// include permissions they were granted during installation. This struct uses
/// `#[serde(default)]` to automatically default missing fields to `PermissionLevel::None`,
/// which provides better ergonomics than `Option<PermissionLevel>` while accurately
/// representing the API semantics (missing permission = no permission).
///
/// # Examples
///
/// ```
/// # use github_bot_sdk::auth::{InstallationPermissions, PermissionLevel};
/// // Partial permissions from GitHub API (only metadata and contents)
/// let json = r#"{"metadata": "read", "contents": "read"}"#;
/// let perms: InstallationPermissions = serde_json::from_str(json).unwrap();
///
/// assert_eq!(perms.metadata, PermissionLevel::Read);
/// assert_eq!(perms.contents, PermissionLevel::Read);
/// assert_eq!(perms.issues, PermissionLevel::None);  // Defaulted
/// assert_eq!(perms.pull_requests, PermissionLevel::None);  // Defaulted
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct InstallationPermissions {
    pub issues: PermissionLevel,
    pub pull_requests: PermissionLevel,
    pub contents: PermissionLevel,
    pub metadata: PermissionLevel,
    pub checks: PermissionLevel,
    pub actions: PermissionLevel,
}

impl Default for InstallationPermissions {
    fn default() -> Self {
        Self {
            issues: PermissionLevel::None,
            pull_requests: PermissionLevel::None,
            contents: PermissionLevel::None,
            metadata: PermissionLevel::None,
            checks: PermissionLevel::None,
            actions: PermissionLevel::None,
        }
    }
}

/// Permission level for GitHub resources.
///
/// Represents the access level granted for a specific permission.
/// Defaults to `None` when not specified.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum PermissionLevel {
    #[default]
    None,
    Read,
    Write,
    Admin,
}

/// Specific permissions that can be checked on tokens.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Permission {
    ReadIssues,
    WriteIssues,
    ReadPullRequests,
    WritePullRequests,
    ReadContents,
    WriteContents,
    ReadChecks,
    WriteChecks,
}

// ============================================================================
// Supporting Types
// ============================================================================

/// User type classification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum UserType {
    User,
    Bot,
    Organization,
}

/// Installation target type (where the app is installed).
///
/// Indicates whether the GitHub App is installed on an organization or user account.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "PascalCase")]
pub enum TargetType {
    Organization,
    User,
}

/// User information from GitHub API.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct User {
    pub id: UserId,
    pub login: String,
    #[serde(rename = "type")]
    pub user_type: UserType,
    pub avatar_url: Option<String>,
    pub html_url: String,
}

/// Account information for installations.
///
/// Similar to User but represents the account where a GitHub App is installed.
/// This can be either an organization or a user account.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Account {
    pub id: UserId,
    pub login: String,
    #[serde(rename = "type")]
    pub account_type: TargetType,
    pub avatar_url: Option<String>,
    pub html_url: String,
}

/// Repository information from GitHub API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Repository {
    pub id: RepositoryId,
    pub name: String,
    pub full_name: String,
    pub owner: User,
    pub private: bool,
    pub html_url: String,
    pub default_branch: String,
}

impl Repository {
    /// Create a new repository.
    pub fn new(
        id: RepositoryId,
        name: String,
        full_name: String,
        owner: User,
        private: bool,
    ) -> Self {
        Self {
            id,
            name: name.clone(),
            full_name: full_name.clone(),
            owner,
            private,
            html_url: format!("https://github.com/{}", full_name),
            default_branch: "main".to_string(), // Default assumption
        }
    }

    /// Get repository owner name.
    pub fn owner_name(&self) -> &str {
        &self.owner.login
    }

    /// Get repository name without owner.
    pub fn repo_name(&self) -> &str {
        &self.name
    }

    /// Get full repository name (owner/name).
    pub fn full_name(&self) -> &str {
        &self.full_name
    }
}

/// Installation information from GitHub API.
///
/// Represents a GitHub App installation on an organization or user account.
/// Includes permissions, repository access, and subscription information.
///
/// # Examples
///
/// ```no_run
/// # use github_bot_sdk::auth::{Installation, TargetType};
/// # fn example(installation: Installation) {
/// match installation.target_type {
///     TargetType::Organization => {
///         println!("Installed on organization: {}", installation.account.login);
///     }
///     TargetType::User => {
///         println!("Installed on user: {}", installation.account.login);
///     }
/// }
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Installation {
    pub id: InstallationId,
    pub account: Account,
    pub access_tokens_url: String,
    pub repositories_url: String,
    pub html_url: String,
    pub app_id: GitHubAppId,
    pub target_type: TargetType,
    pub repository_selection: RepositorySelection,
    pub permissions: InstallationPermissions,
    pub events: Vec<String>,
    pub created_at: DateTime<Utc>,
    pub updated_at: DateTime<Utc>,
    #[serde(default)]
    pub single_file_name: Option<String>,
    #[serde(default)]
    pub has_multiple_single_files: bool,
    pub suspended_at: Option<DateTime<Utc>>,
    pub suspended_by: Option<User>,
}

/// Repository selection for an installation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RepositorySelection {
    All,
    Selected,
}

/// Private key for JWT signing.
///
/// Stores the cryptographic key material for signing JWTs. The key data
/// is never exposed in Debug output for security.
#[derive(Clone)]
pub struct PrivateKey {
    key_data: Vec<u8>,
    algorithm: KeyAlgorithm,
}

impl PrivateKey {
    /// Create a new private key.
    ///
    /// # Arguments
    ///
    /// * `key_data` - The raw key bytes (PEM or DER format)
    /// * `algorithm` - The signing algorithm (typically RS256)
    pub fn new(key_data: Vec<u8>, algorithm: KeyAlgorithm) -> Self {
        Self {
            key_data,
            algorithm,
        }
    }

    /// Get the key data.
    pub fn key_data(&self) -> &[u8] {
        &self.key_data
    }

    /// Get the signing algorithm.
    pub fn algorithm(&self) -> &KeyAlgorithm {
        &self.algorithm
    }
}

// Security: Don't expose key data in debug output
impl std::fmt::Debug for PrivateKey {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PrivateKey")
            .field("algorithm", &self.algorithm)
            .field("key_data", &"<REDACTED>")
            .finish()
    }
}

/// Key algorithm for JWT signing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyAlgorithm {
    RS256,
}

/// JWT claims structure for GitHub App authentication.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwtClaims {
    /// Issuer (GitHub App ID)
    pub iss: GitHubAppId,
    /// Issued at (Unix timestamp)
    pub iat: i64,
    /// Expiration (Unix timestamp, max 10 minutes from iat)
    pub exp: i64,
}

/// Rate limit information from GitHub API.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitInfo {
    pub limit: u32,
    pub remaining: u32,
    pub reset_at: DateTime<Utc>,
    pub used: u32,
}

// ============================================================================
// Trait Definitions (Interfaces for later tasks)
// ============================================================================

/// Main interface for GitHub App authentication operations.
///
/// Provides two authentication levels:
/// - **App-level**: JWT tokens for operations as the GitHub App (discovering installations, managing app)
/// - **Installation-level**: Installation tokens for operations within a specific installation context
///
/// See `docs/spec/architecture/app-level-authentication.md` for detailed usage patterns.
#[async_trait::async_trait]
pub trait AuthenticationProvider: Send + Sync {
    /// Get JWT token for app-level GitHub API operations.
    ///
    /// Use this for operations that require authentication as the GitHub App itself, such as:
    /// - Listing installations (`GET /app/installations`)
    /// - Getting app information (`GET /app`)
    /// - Managing installations (`GET /app/installations/{installation_id}`)
    ///
    /// This method handles caching and automatic refresh of JWTs.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use github_bot_sdk::auth::AuthenticationProvider;
    /// # use github_bot_sdk::error::AuthError;
    /// # async fn example(auth: &dyn AuthenticationProvider) -> Result<(), AuthError> {
    /// // Get JWT for app-level operations
    /// let jwt = auth.app_token().await?;
    /// // Use jwt.token() in Authorization: Bearer header
    /// # Ok(())
    /// # }
    /// ```
    async fn app_token(&self) -> Result<JsonWebToken, AuthError>;

    /// Get installation token for installation-level API operations.
    ///
    /// Use this for operations within a specific installation context, such as:
    /// - Repository operations (reading files, creating issues/PRs)
    /// - Organization operations (team management, webhooks)
    /// - Any operation scoped to the installation's permissions
    ///
    /// This method handles caching and automatic refresh of installation tokens.
    ///
    /// # Arguments
    ///
    /// * `installation_id` - The installation to get a token for
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use github_bot_sdk::auth::{AuthenticationProvider, InstallationId};
    /// # use github_bot_sdk::error::AuthError;
    /// # async fn example(auth: &dyn AuthenticationProvider) -> Result<(), AuthError> {
    /// let installation_id = InstallationId::new(123456);
    /// let token = auth.installation_token(installation_id).await?;
    /// // Use token.token() in Authorization: Bearer header
    /// # Ok(())
    /// # }
    /// ```
    async fn installation_token(
        &self,
        installation_id: InstallationId,
    ) -> Result<InstallationToken, AuthError>;

    /// Refresh installation token (force new token generation).
    ///
    /// Bypasses cache and requests a new installation token from GitHub.
    /// Use sparingly as it counts against rate limits.
    async fn refresh_installation_token(
        &self,
        installation_id: InstallationId,
    ) -> Result<InstallationToken, AuthError>;

    /// List all installations for this GitHub App.
    ///
    /// Requires app-level authentication. This is a convenience method that combines
    /// app_token() with the list installations API call.
    async fn list_installations(&self) -> Result<Vec<Installation>, AuthError>;

    /// Get repositories accessible by installation.
    ///
    /// Requires installation-level authentication. This is a convenience method that combines
    /// installation_token() with the list repositories API call.
    async fn get_installation_repositories(
        &self,
        installation_id: InstallationId,
    ) -> Result<Vec<Repository>, AuthError>;
}

/// Interface for retrieving GitHub App secrets from secure storage.
#[async_trait::async_trait]
pub trait SecretProvider: Send + Sync {
    /// Get private key for JWT signing.
    async fn get_private_key(&self) -> Result<PrivateKey, SecretError>;

    /// Get GitHub App ID.
    async fn get_app_id(&self) -> Result<GitHubAppId, SecretError>;

    /// Get webhook secret for signature validation.
    async fn get_webhook_secret(&self) -> Result<String, SecretError>;

    /// Get cache duration for secrets.
    fn cache_duration(&self) -> Duration;
}

/// Interface for caching authentication tokens securely.
#[async_trait::async_trait]
pub trait TokenCache: Send + Sync {
    /// Get cached JWT token.
    async fn get_jwt(&self, app_id: GitHubAppId) -> Result<Option<JsonWebToken>, CacheError>;

    /// Store JWT token in cache.
    async fn store_jwt(&self, jwt: JsonWebToken) -> Result<(), CacheError>;

    /// Get cached installation token.
    async fn get_installation_token(
        &self,
        installation_id: InstallationId,
    ) -> Result<Option<InstallationToken>, CacheError>;

    /// Store installation token in cache.
    async fn store_installation_token(&self, token: InstallationToken) -> Result<(), CacheError>;

    /// Invalidate installation token.
    async fn invalidate_installation_token(
        &self,
        installation_id: InstallationId,
    ) -> Result<(), CacheError>;

    /// Cleanup expired tokens.
    fn cleanup_expired_tokens(&self);
}

/// Interface for JWT token generation and signing.
#[async_trait::async_trait]
pub trait JwtSigner: Send + Sync {
    /// Sign JWT with private key.
    async fn sign_jwt(
        &self,
        claims: JwtClaims,
        private_key: &PrivateKey,
    ) -> Result<JsonWebToken, SigningError>;

    /// Validate private key format.
    fn validate_private_key(&self, key: &PrivateKey) -> Result<(), ValidationError>;
}

/// Interface for GitHub API client operations.
#[async_trait::async_trait]
pub trait GitHubApiClient: Send + Sync {
    /// Create installation access token via GitHub API.
    async fn create_installation_access_token(
        &self,
        installation_id: InstallationId,
        jwt: &JsonWebToken,
    ) -> Result<InstallationToken, ApiError>;

    /// List installations for the GitHub App.
    async fn list_app_installations(
        &self,
        jwt: &JsonWebToken,
    ) -> Result<Vec<Installation>, ApiError>;

    /// Get repositories for installation.
    async fn list_installation_repositories(
        &self,
        installation_id: InstallationId,
        token: &InstallationToken,
    ) -> Result<Vec<Repository>, ApiError>;

    /// Get repository information.
    async fn get_repository(
        &self,
        repo_id: RepositoryId,
        token: &InstallationToken,
    ) -> Result<Repository, ApiError>;

    /// Check API rate limits.
    async fn get_rate_limit(&self, token: &InstallationToken) -> Result<RateLimitInfo, ApiError>;
}

// ============================================================================
// Submodules
// ============================================================================

pub mod cache;
pub mod jwt;
pub mod tokens;

#[cfg(test)]
#[path = "mod_tests.rs"]
mod tests;