Capability.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. /**
  3. * Twilio Capability Token generator
  4. *
  5. * @category Services
  6. * @package Services_Twilio
  7. * @author Jeff Lindsay <jeff.lindsay@twilio.com>
  8. * @license http://creativecommons.org/licenses/MIT/ MIT
  9. */
  10. class Services_Twilio_Capability
  11. {
  12. public $accountSid;
  13. public $authToken;
  14. public $scopes;
  15. /**
  16. * Create a new TwilioCapability with zero permissions. Next steps are to
  17. * grant access to resources by configuring this token through the
  18. * functions allowXXXX.
  19. *
  20. * @param $accountSid the account sid to which this token is granted access
  21. * @param $authToken the secret key used to sign the token. Note, this auth
  22. * token is not visible to the user of the token.
  23. */
  24. public function __construct($accountSid, $authToken)
  25. {
  26. $this->accountSid = $accountSid;
  27. $this->authToken = $authToken;
  28. $this->scopes = array();
  29. $this->clientName = false;
  30. }
  31. /**
  32. * If the user of this token should be allowed to accept incoming
  33. * connections then configure the TwilioCapability through this method and
  34. * specify the client name.
  35. *
  36. * @param $clientName
  37. */
  38. public function allowClientIncoming($clientName)
  39. {
  40. // clientName must be a non-zero length alphanumeric string
  41. if (preg_match('/\W/', $clientName)) {
  42. throw new InvalidArgumentException(
  43. 'Only alphanumeric characters allowed in client name.');
  44. }
  45. if (strlen($clientName) == 0) {
  46. throw new InvalidArgumentException(
  47. 'Client name must not be a zero length string.');
  48. }
  49. $this->clientName = $clientName;
  50. $this->allow('client', 'incoming',
  51. array('clientName' => $clientName));
  52. }
  53. /**
  54. * Allow the user of this token to make outgoing connections.
  55. *
  56. * @param $appSid the application to which this token grants access
  57. * @param $appParams signed parameters that the user of this token cannot
  58. * overwrite.
  59. */
  60. public function allowClientOutgoing($appSid, array $appParams=array())
  61. {
  62. $this->allow('client', 'outgoing', array(
  63. 'appSid' => $appSid,
  64. 'appParams' => http_build_query($appParams, '', '&')));
  65. }
  66. /**
  67. * Allow the user of this token to access their event stream.
  68. *
  69. * @param $filters key/value filters to apply to the event stream
  70. */
  71. public function allowEventStream(array $filters=array())
  72. {
  73. $this->allow('stream', 'subscribe', array(
  74. 'path' => '/2010-04-01/Events',
  75. 'params' => http_build_query($filters, '', '&'),
  76. ));
  77. }
  78. /**
  79. * Generates a new token based on the credentials and permissions that
  80. * previously has been granted to this token.
  81. *
  82. * @param $ttl the expiration time of the token (in seconds). Default
  83. * value is 3600 (1hr)
  84. * @return the newly generated token that is valid for $ttl seconds
  85. */
  86. public function generateToken($ttl = 3600)
  87. {
  88. $payload = array(
  89. 'scope' => array(),
  90. 'iss' => $this->accountSid,
  91. 'exp' => time() + $ttl,
  92. );
  93. $scopeStrings = array();
  94. foreach ($this->scopes as $scope) {
  95. if ($scope->privilege == "outgoing" && $this->clientName)
  96. $scope->params["clientName"] = $this->clientName;
  97. $scopeStrings[] = $scope->toString();
  98. }
  99. $payload['scope'] = implode(' ', $scopeStrings);
  100. return JWT::encode($payload, $this->authToken, 'HS256');
  101. }
  102. protected function allow($service, $privilege, $params) {
  103. $this->scopes[] = new ScopeURI($service, $privilege, $params);
  104. }
  105. }
  106. /**
  107. * Scope URI implementation
  108. *
  109. * Simple way to represent configurable privileges in an OAuth
  110. * friendly way. For our case, they look like this:
  111. *
  112. * scope:<service>:<privilege>?<params>
  113. *
  114. * For example:
  115. * scope:client:incoming?name=jonas
  116. *
  117. * @author Jeff Lindsay <jeff.lindsay@twilio.com>
  118. */
  119. class ScopeURI
  120. {
  121. public $service;
  122. public $privilege;
  123. public $params;
  124. public function __construct($service, $privilege, $params = array())
  125. {
  126. $this->service = $service;
  127. $this->privilege = $privilege;
  128. $this->params = $params;
  129. }
  130. public function toString()
  131. {
  132. $uri = "scope:{$this->service}:{$this->privilege}";
  133. if (count($this->params)) {
  134. $uri .= "?".http_build_query($this->params, '', '&');
  135. }
  136. return $uri;
  137. }
  138. /**
  139. * Parse a scope URI into a ScopeURI object
  140. *
  141. * @param string $uri The scope URI
  142. * @return ScopeURI The parsed scope uri
  143. */
  144. public static function parse($uri)
  145. {
  146. if (strpos($uri, 'scope:') !== 0) {
  147. throw new UnexpectedValueException(
  148. 'Not a scope URI according to scheme');
  149. }
  150. $parts = explode('?', $uri, 1);
  151. $params = null;
  152. if (count($parts) > 1) {
  153. parse_str($parts[1], $params);
  154. }
  155. $parts = explode(':', $parts[0], 2);
  156. if (count($parts) != 3) {
  157. throw new UnexpectedValueException(
  158. 'Not enough parts for scope URI');
  159. }
  160. list($scheme, $service, $privilege) = $parts;
  161. return new ScopeURI($service, $privilege, $params);
  162. }
  163. }
  164. /**
  165. * JSON Web Token implementation
  166. *
  167. * Minimum implementation used by Realtime auth, based on this spec:
  168. * http://self-issued.info/docs/draft-jones-json-web-token-01.html.
  169. *
  170. * @author Neuman Vong <neuman@twilio.com>
  171. */
  172. class JWT
  173. {
  174. /**
  175. * @param string $jwt The JWT
  176. * @param string|null $key The secret key
  177. * @param bool $verify Don't skip verification process
  178. *
  179. * @return object The JWT's payload as a PHP object
  180. */
  181. public static function decode($jwt, $key = null, $verify = true)
  182. {
  183. $tks = explode('.', $jwt);
  184. if (count($tks) != 3) {
  185. throw new UnexpectedValueException('Wrong number of segments');
  186. }
  187. list($headb64, $payloadb64, $cryptob64) = $tks;
  188. if (null === ($header = JWT::jsonDecode(JWT::urlsafeB64Decode($headb64)))
  189. ) {
  190. throw new UnexpectedValueException('Invalid segment encoding');
  191. }
  192. if (null === $payload = JWT::jsonDecode(JWT::urlsafeB64Decode($payloadb64))
  193. ) {
  194. throw new UnexpectedValueException('Invalid segment encoding');
  195. }
  196. $sig = JWT::urlsafeB64Decode($cryptob64);
  197. if ($verify) {
  198. if (empty($header->alg)) {
  199. throw new DomainException('Empty algorithm');
  200. }
  201. if ($sig != JWT::sign("$headb64.$payloadb64", $key, $header->alg)) {
  202. throw new UnexpectedValueException('Signature verification failed');
  203. }
  204. }
  205. return $payload;
  206. }
  207. /**
  208. * @param object|array $payload PHP object or array
  209. * @param string $key The secret key
  210. * @param string $algo The signing algorithm
  211. *
  212. * @return string A JWT
  213. */
  214. public static function encode($payload, $key, $algo = 'HS256')
  215. {
  216. $header = array('typ' => 'JWT', 'alg' => $algo);
  217. $segments = array();
  218. $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($header));
  219. $segments[] = JWT::urlsafeB64Encode(JWT::jsonEncode($payload));
  220. $signing_input = implode('.', $segments);
  221. $signature = JWT::sign($signing_input, $key, $algo);
  222. $segments[] = JWT::urlsafeB64Encode($signature);
  223. return implode('.', $segments);
  224. }
  225. /**
  226. * @param string $msg The message to sign
  227. * @param string $key The secret key
  228. * @param string $method The signing algorithm
  229. *
  230. * @return string An encrypted message
  231. */
  232. public static function sign($msg, $key, $method = 'HS256')
  233. {
  234. $methods = array(
  235. 'HS256' => 'sha256',
  236. 'HS384' => 'sha384',
  237. 'HS512' => 'sha512',
  238. );
  239. if (empty($methods[$method])) {
  240. throw new DomainException('Algorithm not supported');
  241. }
  242. return hash_hmac($methods[$method], $msg, $key, true);
  243. }
  244. /**
  245. * @param string $input JSON string
  246. *
  247. * @return object Object representation of JSON string
  248. */
  249. public static function jsonDecode($input)
  250. {
  251. $obj = json_decode($input);
  252. if (function_exists('json_last_error') && $errno = json_last_error()) {
  253. JWT::handleJsonError($errno);
  254. }
  255. else if ($obj === null && $input !== 'null') {
  256. throw new DomainException('Null result with non-null input');
  257. }
  258. return $obj;
  259. }
  260. /**
  261. * @param object|array $input A PHP object or array
  262. *
  263. * @return string JSON representation of the PHP object or array
  264. */
  265. public static function jsonEncode($input)
  266. {
  267. $json = json_encode($input);
  268. if (function_exists('json_last_error') && $errno = json_last_error()) {
  269. JWT::handleJsonError($errno);
  270. }
  271. else if ($json === 'null' && $input !== null) {
  272. throw new DomainException('Null result with non-null input');
  273. }
  274. return $json;
  275. }
  276. /**
  277. * @param string $input A base64 encoded string
  278. *
  279. * @return string A decoded string
  280. */
  281. public static function urlsafeB64Decode($input)
  282. {
  283. $padlen = 4 - strlen($input) % 4;
  284. $input .= str_repeat('=', $padlen);
  285. return base64_decode(strtr($input, '-_', '+/'));
  286. }
  287. /**
  288. * @param string $input Anything really
  289. *
  290. * @return string The base64 encode of what you passed in
  291. */
  292. public static function urlsafeB64Encode($input)
  293. {
  294. return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
  295. }
  296. /**
  297. * @param int $errno An error number from json_last_error()
  298. *
  299. * @return void
  300. */
  301. private static function handleJsonError($errno)
  302. {
  303. $messages = array(
  304. JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
  305. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  306. JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON'
  307. );
  308. throw new DomainException(isset($messages[$errno])
  309. ? $messages[$errno]
  310. : 'Unknown JSON error: ' . $errno
  311. );
  312. }
  313. }