AbstractSignature.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. <?php
  2. /**
  3. * Copyright 2019 Huawei Technologies Co.,Ltd.
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  5. * this file except in compliance with the License. You may obtain a copy of the
  6. * License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed
  11. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. * specific language governing permissions and limitations under the License.
  14. *
  15. */
  16. namespace Obs\Internal\Signature;
  17. use GuzzleHttp\Psr7\Stream;
  18. use Obs\Internal\Common\Model;
  19. use Obs\Internal\Common\ObsTransform;
  20. use Obs\Internal\Common\SchemaFormatter;
  21. use Obs\Internal\Common\V2Transform;
  22. use Obs\Internal\Resource\Constants;
  23. use Obs\Log\ObsLog;
  24. use Obs\ObsException;
  25. use Psr\Http\Message\StreamInterface;
  26. abstract class AbstractSignature implements SignatureInterface
  27. {
  28. protected $ak;
  29. protected $sk;
  30. protected $pathStyle;
  31. protected $endpoint;
  32. protected $methodName;
  33. protected $securityToken;
  34. protected $signature;
  35. protected $isCname;
  36. public static function urlencodeWithSafe($val, $safe = '/')
  37. {
  38. $len = strlen($val);
  39. if ($len === 0) {
  40. return '';
  41. }
  42. $buffer = [];
  43. for ($index = 0; $index < $len; $index++) {
  44. $str = $val[$index];
  45. $pos = strpos($safe, $str);
  46. $buffer[] = !$pos && $pos !== 0 ? rawurlencode($str) : $str;
  47. }
  48. return implode('', $buffer);
  49. }
  50. protected function __construct($ak, $sk, $pathStyle, $endpoint, $methodName, $signature, $securityToken = false, $isCname = false)
  51. {
  52. $this->ak = $ak;
  53. $this->sk = $sk;
  54. $this->pathStyle = $pathStyle;
  55. $this->endpoint = $endpoint;
  56. $this->methodName = $methodName;
  57. $this->signature = $signature;
  58. $this->securityToken = $securityToken;
  59. $this->isCname = $isCname;
  60. }
  61. protected function transXmlByType($key, &$value, &$subParams, $transHolder)
  62. {
  63. $xml = [];
  64. $treatAsString = false;
  65. if (isset($value['type'])) {
  66. $type = $value['type'];
  67. if ($type === 'array') {
  68. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  69. $subXml = [];
  70. foreach ($subParams as $item) {
  71. $temp = $this->transXmlByType($key, $value['items'], $item, $transHolder);
  72. if ($temp !== '') {
  73. $subXml[] = $temp;
  74. }
  75. }
  76. if (!empty($subXml)) {
  77. if (!isset($value['data']['xmlFlattened'])) {
  78. $xml[] = '<' . $name . '>';
  79. $xml[] = implode('', $subXml);
  80. $xml[] = '</' . $name . '>';
  81. } else {
  82. $xml[] = implode('', $subXml);
  83. }
  84. }
  85. } elseif ($type === 'object') {
  86. $name = $this->getNameByObjectType($key, $value);
  87. $properties = $value['properties'];
  88. $subXml = [];
  89. $attr = [];
  90. foreach ($properties as $pkey => $pvalue) {
  91. if (isset($pvalue['required']) && $pvalue['required'] && !isset($subParams[$pkey])) {
  92. $obsException = new ObsException('param:' . $pkey . ' is required');
  93. $obsException->setExceptionType('client');
  94. throw $obsException;
  95. }
  96. if (isset($subParams[$pkey])) {
  97. if (isset($pvalue['data'])
  98. && isset($pvalue['data']['xmlAttribute'])
  99. && $pvalue['data']['xmlAttribute']
  100. ) {
  101. $attrValue = $this->xmlTransfer(trim(strval($subParams[$pkey])));
  102. $attr[$pvalue['sentAs']] = '"' . $attrValue . '"';
  103. if (isset($pvalue['data']['xmlNamespace'])) {
  104. $ns = substr($pvalue['sentAs'], 0, strpos($pvalue['sentAs'], ':'));
  105. $attr['xmlns:' . $ns] = '"' . $pvalue['data']['xmlNamespace'] . '"';
  106. }
  107. } else {
  108. $subXml[] = $this->transXmlByType($pkey, $pvalue, $subParams[$pkey], $transHolder);
  109. }
  110. }
  111. }
  112. $val = implode('', $subXml);
  113. if ($val !== '') {
  114. $newName = $name;
  115. if (!empty($attr)) {
  116. foreach ($attr as $akey => $avalue) {
  117. $newName .= ' ' . $akey . '=' . $avalue;
  118. }
  119. }
  120. if (!isset($value['data']['xmlFlattened'])) {
  121. $xml[] = '<' . $newName . '>';
  122. $xml[] = $val;
  123. $xml[] = '</' . $name . '>';
  124. } else {
  125. $xml[] = $val;
  126. }
  127. }
  128. } else {
  129. $treatAsString = true;
  130. }
  131. } else {
  132. $treatAsString = true;
  133. $type = null;
  134. }
  135. if ($treatAsString) {
  136. if ($type === 'boolean') {
  137. if (!is_bool($subParams) && strval($subParams) !== 'false' && strval($subParams) !== 'true') {
  138. $obsException = new ObsException('param:' . $key . ' is not a boolean value');
  139. $obsException->setExceptionType('client');
  140. throw $obsException;
  141. }
  142. } elseif ($type === 'numeric') {
  143. if (!is_numeric($subParams)) {
  144. $obsException = new ObsException('param:' . $key . ' is not a numeric value');
  145. $obsException->setExceptionType('client');
  146. throw $obsException;
  147. }
  148. } elseif ($type === 'float') {
  149. if (!is_float($subParams)) {
  150. $obsException = new ObsException('param:' . $key . ' is not a float value');
  151. $obsException->setExceptionType('client');
  152. throw $obsException;
  153. }
  154. } elseif ($type === 'int' || $type === 'integer') {
  155. if (!is_int($subParams)) {
  156. $obsException = new ObsException('param:' . $key . ' is not a int value');
  157. $obsException->setExceptionType('client');
  158. throw $obsException;
  159. }
  160. } else {
  161. // nothing handle
  162. }
  163. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  164. if (is_bool($subParams)) {
  165. $val = $subParams ? 'true' : 'false';
  166. } else {
  167. $val = strval($subParams);
  168. }
  169. if (isset($value['format'])) {
  170. $val = SchemaFormatter::format($value['format'], $val);
  171. }
  172. if (isset($value['transform'])) {
  173. $val = $transHolder->transform($value['transform'], $val);
  174. }
  175. if (isset($val) && $val !== '') {
  176. $val = $this->xmlTransfer($val);
  177. if (!isset($value['data']['xmlFlattened'])) {
  178. $xml[] = '<' . $name . '>';
  179. $xml[] = $val;
  180. $xml[] = '</' . $name . '>';
  181. } else {
  182. $xml[] = $val;
  183. }
  184. } elseif (isset($value['canEmpty']) && $value['canEmpty']) {
  185. $xml[] = '<' . $name . '>';
  186. $xml[] = $val;
  187. $xml[] = '</' . $name . '>';
  188. } else {
  189. // nothing handle
  190. }
  191. }
  192. $ret = implode('', $xml);
  193. if (isset($value['wrapper'])) {
  194. $ret = '<' . $value['wrapper'] . '>' . $ret . '</' . $value['wrapper'] . '>';
  195. }
  196. return $ret;
  197. }
  198. private function xmlTransfer($tag)
  199. {
  200. $search = array('&', '<', '>', '\'', '"');
  201. $repalce = array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;');
  202. return str_replace($search, $repalce, $tag);
  203. }
  204. private function getNameByObjectType($key, $value)
  205. {
  206. return isset($value['sentAs']) ? $value['sentAs'] : (isset($value['name']) ? $value['name'] : $key);
  207. }
  208. private function getNameByArrayType($key, $value)
  209. {
  210. return isset($value['sentAs']) ? $value['sentAs'] : (isset($value['items']['sentAs']) ? $value['items']['sentAs'] : $key);
  211. }
  212. protected function prepareAuth(array &$requestConfig, array &$params, Model $model)
  213. {
  214. $transHolder = strcasecmp($this->signature, 'obs') === 0
  215. ? ObsTransform::getInstance()
  216. : V2Transform::getInstance();
  217. $method = $requestConfig['httpMethod'];
  218. $requestUrl = $this->endpoint;
  219. $headers = [];
  220. $pathArgs = [];
  221. $dnsParam = null;
  222. $uriParam = null;
  223. $body = [];
  224. $xml = [];
  225. if (isset($requestConfig['specialParam'])) {
  226. $pathArgs[$requestConfig['specialParam']] = '';
  227. }
  228. $result = ['body' => null];
  229. $url = parse_url($requestUrl);
  230. $host = $url['host'];
  231. $fileFlag = false;
  232. if (isset($requestConfig['requestParameters'])) {
  233. $paramsMetadata = $requestConfig['requestParameters'];
  234. foreach ($paramsMetadata as $key => $value) {
  235. if (isset($value['required']) && $value['required'] && !isset($params[$key])) {
  236. $obsException = new ObsException('param:' . $key . ' is required');
  237. $obsException->setExceptionType('client');
  238. throw $obsException;
  239. }
  240. if (isset($params[$key]) && isset($value['location'])) {
  241. $location = $value['location'];
  242. $val = $params[$key];
  243. $type = 'string';
  244. if ($val !== '' && isset($value['type'])) {
  245. $type = $value['type'];
  246. if ($type === 'boolean') {
  247. if (!is_bool($val) && strval($val) !== 'false' && strval($val) !== 'true') {
  248. $obsException = new ObsException('param:' . $key . ' is not a boolean value');
  249. $obsException->setExceptionType('client');
  250. throw $obsException;
  251. }
  252. } elseif ($type === 'numeric') {
  253. if (!is_numeric($val)) {
  254. $obsException = new ObsException('param:' . $key . ' is not a numeric value');
  255. $obsException->setExceptionType('client');
  256. throw $obsException;
  257. }
  258. } elseif ($type === 'float') {
  259. if (!is_float($val)) {
  260. $obsException = new ObsException('param:' . $key . ' is not a float value');
  261. $obsException->setExceptionType('client');
  262. throw $obsException;
  263. }
  264. } elseif ($type === 'int' || $type === 'integer') {
  265. if (!is_int($val)) {
  266. $obsException = new ObsException('param:' . $key . ' is not a int value');
  267. $obsException->setExceptionType('client');
  268. throw $obsException;
  269. }
  270. } else {
  271. // nothing handle
  272. }
  273. }
  274. if ($location === 'header') {
  275. if ($type === 'object') {
  276. if (is_array($val)) {
  277. $sentAs = strtolower($value['sentAs']);
  278. foreach ($val as $k => $v) {
  279. $k = AbstractSignature::urlencodeWithSafe(strtolower($k), ' ;/?:@&=+$,');
  280. $name = strpos($k, $sentAs) === 0 ? $k : $sentAs . $k;
  281. $headers[$name] = AbstractSignature::urlencodeWithSafe($v, ' ;/?:@&=+$,\'*');
  282. }
  283. }
  284. } elseif ($type === 'array') {
  285. if (is_array($val)) {
  286. $name = $this->getNameByArrayType($key, $value);
  287. $temp = [];
  288. foreach ($val as $v) {
  289. $v = strval($v);
  290. if ($v !== '') {
  291. $temp[] = AbstractSignature::urlencodeWithSafe($val, ' ;/?:@&=+$,\'*');
  292. }
  293. }
  294. $headers[$name] = $temp;
  295. }
  296. } elseif ($type === 'password') {
  297. $val = strval($val);
  298. if ($val !== '') {
  299. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  300. $pwdName = isset($value['pwdSentAs']) ? $value['pwdSentAs'] : $name . '-MD5';
  301. $headers[$name] = base64_encode($val);
  302. $headers[$pwdName] = base64_encode(md5($val, true));
  303. }
  304. } else {
  305. if (isset($value['transform'])) {
  306. $val = $transHolder->transform($value['transform'], strval($val));
  307. }
  308. if (isset($val)) {
  309. if (is_bool($val)) {
  310. $val = $val ? 'true' : 'false';
  311. } else {
  312. $val = strval($val);
  313. }
  314. if ($val !== '') {
  315. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  316. if (isset($value['format'])) {
  317. $val = SchemaFormatter::format($value['format'], $val);
  318. }
  319. $headers[$name] = AbstractSignature::urlencodeWithSafe($val, ' ;/?:@&=+$,\'*');
  320. }
  321. }
  322. }
  323. } elseif ($location === 'uri' && $uriParam === null) {
  324. $uriParam = AbstractSignature::urlencodeWithSafe($val);
  325. } elseif ($location === 'dns' && $dnsParam === null) {
  326. $dnsParam = $val;
  327. } elseif ($location === 'query') {
  328. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  329. if (strval($val) !== '') {
  330. if (strcasecmp($this->signature, 'v4') === 0) {
  331. $pathArgs[rawurlencode($name)] = rawurlencode(strval($val));
  332. } else {
  333. $pathArgs[AbstractSignature::urlencodeWithSafe($name)] = AbstractSignature::urlencodeWithSafe(strval($val));
  334. }
  335. }
  336. } elseif ($location === 'xml') {
  337. $val = $this->transXmlByType($key, $value, $val, $transHolder);
  338. if ($val !== '') {
  339. $xml[] = $val;
  340. }
  341. } elseif ($location === 'body') {
  342. if (isset($result['body'])) {
  343. $obsException = new ObsException('duplicated body provided');
  344. $obsException->setExceptionType('client');
  345. throw $obsException;
  346. }
  347. if ($type === 'file') {
  348. if (!file_exists($val)) {
  349. $obsException = new ObsException('file[' . $val . '] does not exist');
  350. $obsException->setExceptionType('client');
  351. throw $obsException;
  352. }
  353. $result['body'] = new Stream(fopen($val, 'r'));
  354. $fileFlag = true;
  355. } elseif ($type === 'stream') {
  356. $result['body'] = $val;
  357. } elseif ($type === 'json') {
  358. $jsonData = json_encode($val);
  359. if (!$jsonData) {
  360. $obsException = new ObsException('input is invalid, since it is not json data');
  361. $obsException->setExceptionType('client');
  362. throw $obsException;
  363. }
  364. $result['body'] = strval($jsonData);
  365. } else {
  366. $result['body'] = strval($val);
  367. }
  368. } elseif ($location === 'response') {
  369. $model[$key] = ['value' => $val, 'type' => $type];
  370. } else {
  371. // nothing handle
  372. }
  373. }
  374. }
  375. if ($dnsParam) {
  376. if ($this->pathStyle) {
  377. $requestUrl = $requestUrl . '/' . $dnsParam;
  378. } else {
  379. $defaultPort = strtolower($url['scheme']) === 'https' ? '443' : '80';
  380. $host = $this->isCname ? $host : $dnsParam . '.' . $host;
  381. $port = isset($url['port']) ? $url['port'] : $defaultPort;
  382. $requestUrl = $url['scheme'] . '://' . $host . ':' . $port;
  383. }
  384. }
  385. if ($uriParam) {
  386. $requestUrl = $requestUrl . '/' . $uriParam;
  387. }
  388. if (!empty($pathArgs)) {
  389. $requestUrl .= '?';
  390. $newPathArgs = [];
  391. foreach ($pathArgs as $key => $value) {
  392. $newPathArgs[] = $value === null || $value === '' ? $key : $key . '=' . $value;
  393. }
  394. $requestUrl .= implode('&', $newPathArgs);
  395. }
  396. }
  397. if ($xml || (isset($requestConfig['data']['xmlAllowEmpty']) && $requestConfig['data']['xmlAllowEmpty'])) {
  398. $body[] = '<';
  399. $xmlRoot = $requestConfig['data']['xmlRoot']['name'];
  400. $body[] = $xmlRoot;
  401. $body[] = '>';
  402. $body[] = implode('', $xml);
  403. $body[] = '</';
  404. $body[] = $xmlRoot;
  405. $body[] = '>';
  406. $headers['Content-Type'] = 'application/xml';
  407. $result['body'] = implode('', $body);
  408. ObsLog::commonLog(DEBUG, 'request content ' . $result['body']);
  409. if (isset($requestConfig['data']['contentMd5']) && $requestConfig['data']['contentMd5']) {
  410. $headers['Content-MD5'] = base64_encode(md5($result['body'], true));
  411. }
  412. }
  413. if ($fileFlag && ($result['body'] instanceof StreamInterface)) {
  414. if ($this->methodName === 'uploadPart' && (isset($model['Offset']) || isset($model['PartSize']))) {
  415. $bodySize = $result['body']->getSize();
  416. if (isset($model['Offset'])) {
  417. $offset = intval($model['Offset']['value']);
  418. $offset = $offset >= 0 && $offset < $bodySize ? $offset : 0;
  419. } else {
  420. $offset = 0;
  421. }
  422. if (isset($model['PartSize'])) {
  423. $partSize = intval($model['PartSize']['value']);
  424. $partSize = $partSize > 0 && $partSize <= ($bodySize - $offset) ? $partSize : $bodySize - $offset;
  425. } else {
  426. $partSize = $bodySize - $offset;
  427. }
  428. $result['body']->rewind();
  429. $result['body']->seek($offset);
  430. $headers['Content-Length'] = $partSize;
  431. } elseif (isset($headers['Content-Length'])) {
  432. $bodySize = $result['body']->getSize();
  433. if (intval($headers['Content-Length']) > $bodySize) {
  434. $headers['Content-Length'] = $bodySize;
  435. }
  436. } else {
  437. // nothing handle
  438. }
  439. }
  440. $constants = Constants::selectConstants($this->signature);
  441. if ($this->securityToken) {
  442. $headers[$constants::SECURITY_TOKEN_HEAD] = $this->securityToken;
  443. }
  444. $headers['Host'] = $host;
  445. $result['host'] = $host;
  446. $result['method'] = $method;
  447. $result['headers'] = $headers;
  448. $result['pathArgs'] = $pathArgs;
  449. $result['dnsParam'] = $dnsParam;
  450. $result['uriParam'] = $uriParam;
  451. $result['requestUrl'] = $requestUrl;
  452. return $result;
  453. }
  454. }