AbstractSignature.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  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 Obs\Log\ObsLog;
  18. use Obs\Internal\Resource\Constants;
  19. use Obs\ObsException;
  20. use Obs\Internal\Common\SchemaFormatter;
  21. use GuzzleHttp\Psr7\Stream;
  22. use Obs\Internal\Common\Model;
  23. use Psr\Http\Message\StreamInterface;
  24. use Obs\Internal\Common\ObsTransform;
  25. use Obs\Internal\Common\V2Transform;
  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. public static function urlencodeWithSafe($val, $safe='/'){
  36. if(($len = strlen($val)) === 0){
  37. return '';
  38. }
  39. $buffer = [];
  40. for ($index=0;$index<$len;$index++){
  41. $str = $val[$index];
  42. $buffer[] = !($pos = strpos($safe, $str)) && $pos !== 0 ? rawurlencode($str) : $str;
  43. }
  44. return implode('', $buffer);
  45. }
  46. protected function __construct($ak, $sk, $pathStyle, $endpoint, $methodName, $signature, $securityToken=false)
  47. {
  48. $this -> ak = $ak;
  49. $this -> sk = $sk;
  50. $this -> pathStyle = $pathStyle;
  51. $this -> endpoint = $endpoint;
  52. $this -> methodName = $methodName;
  53. $this -> signature = $signature;
  54. $this -> securityToken = $securityToken;
  55. }
  56. protected function transXmlByType($key, &$value, &$subParams, $transHolder)
  57. {
  58. $xml = [];
  59. $treatAsString = false;
  60. if(isset($value['type'])){
  61. $type = $value['type'];
  62. if($type === 'array'){
  63. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  64. $subXml = [];
  65. foreach($subParams as $item){
  66. $temp = $this->transXmlByType($key, $value['items'], $item, $transHolder);
  67. if($temp !== ''){
  68. $subXml[] = $temp;
  69. }
  70. }
  71. if(!empty($subXml)){
  72. if(!isset($value['data']['xmlFlattened'])){
  73. $xml[] = '<' . $name . '>';
  74. $xml[] = implode('', $subXml);
  75. $xml[] = '</' . $name . '>';
  76. }else{
  77. $xml[] = implode('', $subXml);
  78. }
  79. }
  80. }else if($type === 'object'){
  81. $name = isset($value['sentAs']) ? $value['sentAs'] : (isset($value['name']) ? $value['name'] : $key);
  82. $properties = $value['properties'];
  83. $subXml = [];
  84. $attr = [];
  85. foreach ($properties as $pkey => $pvalue){
  86. if(isset($pvalue['required']) && $pvalue['required'] && !isset($subParams[$pkey])){
  87. $obsException= new ObsException('param:' .$pkey. ' is required');
  88. $obsException-> setExceptionType('client');
  89. throw $obsException;
  90. }
  91. if(isset($subParams[$pkey])){
  92. if(isset($pvalue['data']) && isset($pvalue['data']['xmlAttribute']) && $pvalue['data']['xmlAttribute']){
  93. $attrValue = $this->xml_tansfer(trim(strval($subParams[$pkey])));
  94. $attr[$pvalue['sentAs']] = '"' . $attrValue . '"';
  95. if(isset($pvalue['data']['xmlNamespace'])){
  96. $ns = substr($pvalue['sentAs'], 0, strpos($pvalue['sentAs'], ':'));
  97. $attr['xmlns:' . $ns] = '"' . $pvalue['data']['xmlNamespace'] . '"';
  98. }
  99. }else{
  100. $subXml[] = $this -> transXmlByType($pkey, $pvalue, $subParams[$pkey], $transHolder);
  101. }
  102. }
  103. }
  104. $val = implode('', $subXml);
  105. if($val !== ''){
  106. $_name = $name;
  107. if(!empty($attr)){
  108. foreach ($attr as $akey => $avalue){
  109. $_name .= ' ' . $akey . '=' . $avalue;
  110. }
  111. }
  112. if(!isset($value['data']['xmlFlattened'])){
  113. $xml[] = '<' . $_name . '>';
  114. $xml[] = $val;
  115. $xml[] = '</' . $name . '>';
  116. } else {
  117. $xml[] = $val;
  118. }
  119. }
  120. }else{
  121. $treatAsString = true;
  122. }
  123. }else{
  124. $treatAsString = true;
  125. $type = null;
  126. }
  127. if($treatAsString){
  128. if($type === 'boolean'){
  129. if(!is_bool($subParams) && strval($subParams) !== 'false' && strval($subParams) !== 'true'){
  130. $obsException= new ObsException('param:' .$key. ' is not a boolean value');
  131. $obsException-> setExceptionType('client');
  132. throw $obsException;
  133. }
  134. }else if($type === 'numeric'){
  135. if(!is_numeric($subParams)){
  136. $obsException= new ObsException('param:' .$key. ' is not a numeric value');
  137. $obsException-> setExceptionType('client');
  138. throw $obsException;
  139. }
  140. }else if($type === 'float'){
  141. if(!is_float($subParams)){
  142. $obsException= new ObsException('param:' .$key. ' is not a float value');
  143. $obsException-> setExceptionType('client');
  144. throw $obsException;
  145. }
  146. }else if($type === 'int' || $type === 'integer'){
  147. if(!is_int($subParams)){
  148. $obsException= new ObsException('param:' .$key. ' is not a int value');
  149. $obsException-> setExceptionType('client');
  150. throw $obsException;
  151. }
  152. }
  153. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  154. if(is_bool($subParams)){
  155. $val = $subParams ? 'true' : 'false';
  156. }else{
  157. $val = strval($subParams);
  158. }
  159. if(isset($value['format'])){
  160. $val = SchemaFormatter::format($value['format'], $val);
  161. }
  162. if (isset($value['transform'])) {
  163. $val = $transHolder->transform($value['transform'], $val);
  164. }
  165. if(isset($val) && $val !== ''){
  166. $val = $this->xml_tansfer($val);
  167. if(!isset($value['data']['xmlFlattened'])){
  168. $xml[] = '<' . $name . '>';
  169. $xml[] = $val;
  170. $xml[] = '</' . $name . '>';
  171. } else {
  172. $xml[] = $val;
  173. }
  174. }else if(isset($value['canEmpty']) && $value['canEmpty']){
  175. $xml[] = '<' . $name . '>';
  176. $xml[] = $val;
  177. $xml[] = '</' . $name . '>';
  178. }
  179. }
  180. $ret = implode('', $xml);
  181. if(isset($value['wrapper'])){
  182. $ret = '<'. $value['wrapper'] . '>' . $ret . '</'. $value['wrapper'] . '>';
  183. }
  184. return $ret;
  185. }
  186. private function xml_tansfer($tag) {
  187. $search = array('&', '<', '>', '\'', '"');
  188. $repalce = array('&amp;', '&lt;', '&gt;', '&apos;', '&quot;');
  189. $transferXml = str_replace($search, $repalce, $tag);
  190. return $transferXml;
  191. }
  192. protected function prepareAuth(array &$requestConfig, array &$params, Model $model)
  193. {
  194. $transHolder = strcasecmp($this-> signature, 'obs') === 0 ? ObsTransform::getInstance() : V2Transform::getInstance();
  195. $method = $requestConfig['httpMethod'];
  196. $requestUrl = $this->endpoint;
  197. $headers = [];
  198. $pathArgs = [];
  199. $dnsParam = null;
  200. $uriParam = null;
  201. $body = [];
  202. $xml = [];
  203. if(isset($requestConfig['specialParam'])){
  204. $pathArgs[$requestConfig['specialParam']] = '';
  205. }
  206. $result = ['body' => null];
  207. $url = parse_url($requestUrl);
  208. $host = $url['host'];
  209. $fileFlag = false;
  210. if(isset($requestConfig['requestParameters'])){
  211. $paramsMetadata = $requestConfig['requestParameters'];
  212. foreach ($paramsMetadata as $key => $value){
  213. if(isset($value['required']) && $value['required'] && !isset($params[$key])){
  214. $obsException= new ObsException('param:' .$key. ' is required');
  215. $obsException-> setExceptionType('client');
  216. throw $obsException;
  217. }
  218. if(isset($params[$key]) && isset($value['location'])){
  219. $location = $value['location'];
  220. $val = $params[$key];
  221. $type = 'string';
  222. if($val !== '' && isset($value['type'])){
  223. $type = $value['type'];
  224. if($type === 'boolean'){
  225. if(!is_bool($val) && strval($val) !== 'false' && strval($val) !== 'true'){
  226. $obsException= new ObsException('param:' .$key. ' is not a boolean value');
  227. $obsException-> setExceptionType('client');
  228. throw $obsException;
  229. }
  230. }else if($type === 'numeric'){
  231. if(!is_numeric($val)){
  232. $obsException= new ObsException('param:' .$key. ' is not a numeric value');
  233. $obsException-> setExceptionType('client');
  234. throw $obsException;
  235. }
  236. }else if($type === 'float'){
  237. if(!is_float($val)){
  238. $obsException= new ObsException('param:' .$key. ' is not a float value');
  239. $obsException-> setExceptionType('client');
  240. throw $obsException;
  241. }
  242. }else if($type === 'int' || $type === 'integer'){
  243. if(!is_int($val)){
  244. $obsException= new ObsException('param:' .$key. ' is not a int value');
  245. $obsException-> setExceptionType('client');
  246. throw $obsException;
  247. }
  248. }
  249. }
  250. if($location === 'header'){
  251. if($type === 'object'){
  252. if(is_array($val)){
  253. $sentAs = strtolower($value['sentAs']);
  254. foreach ($val as $k => $v){
  255. $k = self::urlencodeWithSafe(strtolower($k), ' ;/?:@&=+$,');
  256. $name = strpos($k, $sentAs) === 0 ? $k : $sentAs . $k;
  257. $headers[$name] = self::urlencodeWithSafe($v, ' ;/?:@&=+$,\'*');
  258. }
  259. }
  260. }else if($type === 'array'){
  261. if(is_array($val)){
  262. $name = isset($value['sentAs']) ? $value['sentAs'] : (isset($value['items']['sentAs']) ? $value['items']['sentAs'] : $key);
  263. $temp = [];
  264. foreach ($val as $v){
  265. if(($v = strval($v)) !== ''){
  266. $temp[] = self::urlencodeWithSafe($val, ' ;/?:@&=+$,\'*');
  267. }
  268. }
  269. $headers[$name] = $temp;
  270. }
  271. }else if($type === 'password'){
  272. if(($val = strval($val)) !== ''){
  273. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  274. $pwdName = isset($value['pwdSentAs']) ? $value['pwdSentAs'] : $name . '-MD5';
  275. $val1 = base64_encode($val);
  276. $val2 = base64_encode(md5($val, true));
  277. $headers[$name] = $val1;
  278. $headers[$pwdName] = $val2;
  279. }
  280. }else{
  281. if (isset($value['transform'])) {
  282. $val = $transHolder->transform($value['transform'], strval($val));
  283. }
  284. if(isset($val)){
  285. if(is_bool($val)){
  286. $val = $val ? 'true' : 'false';
  287. }else{
  288. $val = strval($val);
  289. }
  290. if($val !== ''){
  291. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  292. if(isset($value['format'])){
  293. $val = SchemaFormatter::format($value['format'], $val);
  294. }
  295. $headers[$name] = self::urlencodeWithSafe($val, ' ;/?:@&=+$,\'*');
  296. }
  297. }
  298. }
  299. }else if($location === 'uri' && $uriParam === null){
  300. $uriParam = self::urlencodeWithSafe($val);
  301. }else if($location === 'dns' && $dnsParam === null){
  302. $dnsParam = $val;
  303. }else if($location === 'query'){
  304. $name = isset($value['sentAs']) ? $value['sentAs'] : $key;
  305. if(strval($val) !== ''){
  306. if (strcasecmp ( $this->signature, 'v4' ) === 0) {
  307. $pathArgs[rawurlencode($name)] = rawurlencode(strval($val));
  308. } else {
  309. $pathArgs[self::urlencodeWithSafe($name)] = self::urlencodeWithSafe(strval($val));
  310. }
  311. }
  312. }else if($location === 'xml'){
  313. $val = $this->transXmlByType($key, $value, $val, $transHolder);
  314. if($val !== ''){
  315. $xml[] = $val;
  316. }
  317. }else if($location === 'body'){
  318. if(isset($result['body'])){
  319. $obsException= new ObsException('duplicated body provided');
  320. $obsException-> setExceptionType('client');
  321. throw $obsException;
  322. }
  323. if($type === 'file'){
  324. if(!file_exists($val)){
  325. $obsException= new ObsException('file[' .$val. '] does not exist');
  326. $obsException-> setExceptionType('client');
  327. throw $obsException;
  328. }
  329. $result['body'] = new Stream(fopen($val, 'r'));
  330. $fileFlag = true;
  331. }else if($type === 'stream'){
  332. $result['body'] = $val;
  333. }else{
  334. $result['body'] = strval($val);
  335. }
  336. }else if($location === 'response'){
  337. $model[$key] = ['value' => $val, 'type' => $type];
  338. }
  339. }
  340. }
  341. if($dnsParam){
  342. if($this -> pathStyle){
  343. $requestUrl = $requestUrl . '/' . $dnsParam;
  344. }else{
  345. $defaultPort = strtolower($url['scheme']) === 'https' ? '443' : '80';
  346. $host = $dnsParam. '.' . $host;
  347. $requestUrl = $url['scheme'] . '://' . $host . ':' . (isset($url['port']) ? $url['port'] : $defaultPort);
  348. }
  349. }
  350. if($uriParam){
  351. $requestUrl = $requestUrl . '/' . $uriParam;
  352. }
  353. if(!empty($pathArgs)){
  354. $requestUrl .= '?';
  355. $_pathArgs = [];
  356. foreach ($pathArgs as $key => $value){
  357. $_pathArgs[] = $value === null || $value === '' ? $key : $key . '=' . $value;
  358. }
  359. $requestUrl .= implode('&', $_pathArgs);
  360. }
  361. }
  362. if($xml || (isset($requestConfig['data']['xmlAllowEmpty']) && $requestConfig['data']['xmlAllowEmpty'])){
  363. $body[] = '<';
  364. $xmlRoot = $requestConfig['data']['xmlRoot']['name'];
  365. $body[] = $xmlRoot;
  366. $body[] = '>';
  367. $body[] = implode('', $xml);
  368. $body[] = '</';
  369. $body[] = $xmlRoot;
  370. $body[] = '>';
  371. $headers['Content-Type'] = 'application/xml';
  372. $result['body'] = implode('', $body);
  373. ObsLog::commonLog(DEBUG, 'request content ' . $result['body']);
  374. if(isset($requestConfig['data']['contentMd5']) && $requestConfig['data']['contentMd5']){
  375. $headers['Content-MD5'] = base64_encode(md5($result['body'],true));
  376. }
  377. }
  378. if($fileFlag && ($result['body'] instanceof StreamInterface)){
  379. if($this->methodName === 'uploadPart' && (isset($model['Offset']) || isset($model['PartSize']))){
  380. $bodySize = $result['body'] ->getSize();
  381. if(isset($model['Offset'])){
  382. $offset = intval($model['Offset']['value']);
  383. $offset = $offset >= 0 && $offset < $bodySize ? $offset : 0;
  384. }else{
  385. $offset = 0;
  386. }
  387. if(isset($model['PartSize'])){
  388. $partSize = intval($model['PartSize']['value']);
  389. $partSize = $partSize > 0 && $partSize <= ($bodySize - $offset) ? $partSize : $bodySize - $offset;
  390. }else{
  391. $partSize = $bodySize - $offset;
  392. }
  393. $result['body'] -> rewind();
  394. $result['body'] -> seek($offset);
  395. $headers['Content-Length'] = $partSize;
  396. }else if(isset($headers['Content-Length'])){
  397. $bodySize = $result['body'] -> getSize();
  398. if(intval($headers['Content-Length']) > $bodySize){
  399. $headers['Content-Length'] = $bodySize;
  400. }
  401. }
  402. }
  403. $constants = Constants::selectConstants($this -> signature);
  404. if($this->securityToken){
  405. $headers[$constants::SECURITY_TOKEN_HEAD] = $this->securityToken;
  406. }
  407. $headers['Host'] = $host;
  408. $result['host'] = $host;
  409. $result['method'] = $method;
  410. $result['headers'] = $headers;
  411. $result['pathArgs'] = $pathArgs;
  412. $result['dnsParam'] = $dnsParam;
  413. $result['uriParam'] = $uriParam;
  414. $result['requestUrl'] = $requestUrl;
  415. return $result;
  416. }
  417. }