AuthorisationTokenService.vala 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. using Inversion;
  2. using Json;
  3. namespace Spry.Authorisation {
  4. /**
  5. * Service for generating and validating authorisation tokens.
  6. *
  7. * Token Format:
  8. * - JSON payload containing identity data and metadata
  9. * - Signed with Ed25519 (server signing key)
  10. * - Encrypted with X25519 (server sealing key)
  11. * - Base64url encoded
  12. *
  13. * This service uses the same encryption approach as SessionService.
  14. */
  15. public class AuthorisationTokenService : GLib.Object {
  16. private CryptographyProvider _crypto = inject<CryptographyProvider>();
  17. // Configuration
  18. private TimeSpan _token_duration = TimeSpan.HOUR * 24;
  19. /**
  20. * Default token validity duration.
  21. */
  22. public TimeSpan token_duration {
  23. get { return _token_duration; }
  24. set { _token_duration = value; }
  25. }
  26. /**
  27. * Creates a new AuthorisationTokenService with default configuration.
  28. */
  29. public AuthorisationTokenService() {
  30. // Default configuration
  31. }
  32. // =========================================================================
  33. // Token Generation
  34. // =========================================================================
  35. /**
  36. * Generates a signed and encrypted authorisation token for an identity.
  37. *
  38. * @param identity The identity to create a token for
  39. * @param expires_at Optional custom expiry (defaults to token_duration from now)
  40. * @return The encrypted token string
  41. */
  42. public string generate_token(Identity identity, DateTime? expires_at = null) {
  43. // Calculate expiry
  44. DateTime token_expiry;
  45. if (expires_at != null) {
  46. token_expiry = (!)expires_at;
  47. } else {
  48. token_expiry = new DateTime.now_utc().add(_token_duration);
  49. }
  50. // Create token from identity
  51. var duration = token_expiry.difference(new DateTime.now_utc());
  52. var token = new AuthorisationToken.from_identity(identity, duration);
  53. // Serialize to JSON
  54. var json_obj = token.to_json();
  55. var node = new Json.Node(Json.NodeType.OBJECT);
  56. node.set_object(json_obj);
  57. var json_str = Json.to_string(node, false);
  58. // Sign and seal using CryptographyProvider
  59. return _crypto.sign_then_seal_token(json_str, token_expiry);
  60. }
  61. /**
  62. * Generates a token from an existing AuthorisationToken.
  63. *
  64. * @param token The token to serialize and encrypt
  65. * @return The encrypted token string
  66. */
  67. public string generate_token_from_token(AuthorisationToken token) {
  68. var json_str = token.to_json_string();
  69. return _crypto.sign_then_seal_token(json_str, token.expires_at);
  70. }
  71. // =========================================================================
  72. // Token Validation
  73. // =========================================================================
  74. /**
  75. * Validates a token string and returns the parsed token.
  76. *
  77. * This method:
  78. * - Uses CryptographyProvider.unseal_then_verify_token()
  79. * - Checks expiry
  80. * - Parses the JSON payload
  81. *
  82. * @param token_string The encrypted token string
  83. * @return The AuthorisationToken, or null if invalid/expired
  84. */
  85. public AuthorisationToken? parse_token(string token_string) {
  86. try {
  87. // Decrypt and verify the token
  88. var result = _crypto.unseal_then_verify_token(token_string);
  89. if (!result.is_valid) {
  90. return null;
  91. }
  92. // Check if token is expired
  93. if (result.is_expired) {
  94. return null;
  95. }
  96. // Get the payload
  97. var payload = result.payload;
  98. if (payload == null) {
  99. return null;
  100. }
  101. // Parse the JSON
  102. var token = AuthorisationToken.from_json_string((!)payload);
  103. if (token == null) {
  104. return null;
  105. }
  106. // Double-check expiry from the token itself
  107. if (token.is_expired()) {
  108. return null;
  109. }
  110. return token;
  111. } catch (Error e) {
  112. return null;
  113. }
  114. }
  115. /**
  116. * Validates a token and returns detailed validation result.
  117. *
  118. * @param token_string The encrypted token string
  119. * @return A TokenValidationResult with status and token data
  120. */
  121. public TokenValidationResult validate_token(string token_string) {
  122. // Decrypt and verify the token
  123. var crypto_result = _crypto.unseal_then_verify_token(token_string);
  124. if (!crypto_result.is_valid) {
  125. return new TokenValidationResult.failure(
  126. crypto_result.error_message ?? "Invalid token"
  127. );
  128. }
  129. if (crypto_result.is_expired) {
  130. return new TokenValidationResult.failure("Token has expired", true);
  131. }
  132. var payload = crypto_result.payload;
  133. if (payload == null) {
  134. return new TokenValidationResult.failure("Empty token payload");
  135. }
  136. var token = AuthorisationToken.from_json_string((!)payload);
  137. if (token == null) {
  138. return new TokenValidationResult.failure("Failed to parse token payload");
  139. }
  140. // Double-check expiry from the token itself
  141. if (token.is_expired()) {
  142. return new TokenValidationResult.failure("Token has expired", true);
  143. }
  144. return new TokenValidationResult.success(token);
  145. }
  146. }
  147. /**
  148. * Result of token validation containing the token and status information.
  149. */
  150. public class TokenValidationResult : GLib.Object {
  151. /**
  152. * Whether the token was successfully validated.
  153. */
  154. public bool is_valid { get; set; }
  155. /**
  156. * The parsed token, or null if validation failed.
  157. */
  158. public AuthorisationToken? token { get; set; }
  159. /**
  160. * Error message describing why validation failed.
  161. */
  162. public string? error_message { get; set; }
  163. /**
  164. * Whether the token has expired.
  165. */
  166. public bool is_expired { get; set; }
  167. /**
  168. * Creates a successful validation result.
  169. */
  170. public TokenValidationResult.success(AuthorisationToken token) {
  171. GLib.Object(
  172. is_valid: true,
  173. token: token,
  174. error_message: null,
  175. is_expired: false
  176. );
  177. }
  178. /**
  179. * Creates a failed validation result.
  180. */
  181. public TokenValidationResult.failure(string error_message, bool expired = false) {
  182. GLib.Object(
  183. is_valid: false,
  184. token: null,
  185. error_message: error_message,
  186. is_expired: expired
  187. );
  188. }
  189. }
  190. }