public function testBasicOperations() { $inputBucket = 'php-integ-transcoder-test-bucket-input'; $outputBucket = 'php-integ-transcoder-test-bucket-output'; $roleName = 'php-integ-transcoder-test-role'; $policyName = 'php-integ-transcoder-test-policy'; $pipelineName = 'php-integ-transcoder-test-pipeline'; self::log('Create input and output buckets for the Elastic Transcoder pipeline.'); $commands = array(); $commands[] = $this->s3->getCommand('CreateBucket', array('Bucket' => $inputBucket)); $commands[] = $this->s3->getCommand('CreateBucket', array('Bucket' => $outputBucket)); $this->s3->execute($commands); self::log('Create an IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('CreateRole', array('RoleName' => $roleName, 'AssumeRolePolicyDocument' => self::DUMMY_IAM_POLICY_ASSUME_ROLE))->getResult(); $roleArn = $result->getPath('Role/Arn'); self::log('Put a policy on the IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('PutRolePolicy', array('PolicyName' => $policyName, 'RoleName' => $roleName, 'PolicyDocument' => self::DUMMY_IAM_POLICY_ALLOW_S3))->getResult(); self::log('Use TestRole to validate our pipeline inputs. NOTE: Ours are not valid on purpose.'); $result = $this->transcoder->getCommand('TestRole', array('InputBucket' => $inputBucket, 'OutputBucket' => $outputBucket, 'Role' => $roleArn, 'Topics' => array()))->getResult(); $this->assertEquals('false', $result['Success']); self::log('Create an Elastic Transcoder pipeline.'); $result = $this->transcoder->getCommand('CreatePipeline', array('Name' => $pipelineName, 'InputBucket' => $inputBucket, 'OutputBucket' => $outputBucket, 'Role' => $roleArn, 'Notifications' => array_fill_keys(array('Progressing', 'Completed', 'Warning', 'Error'), '')))->getResult(); $pipelineId = $result->getPath('Pipeline/Id'); self::log('Make sure created Elastic Transcoder pipeline is in the list of pipelines.'); $result = $this->transcoder->getCommand('ListPipelines')->getResult(); $pipelineNames = $result->getPath('Pipelines/*/Name'); $this->assertContains($pipelineName, $pipelineNames); self::log('Make sure ListPipelines iterator works.'); $found = false; foreach ($this->transcoder->getIterator('ListPipelines') as $pipeline) { if ($pipeline['Name'] == $pipelineName) { $found = true; break; } } if (!$found) { $this->fail('Did not find the pipeline in the iterator results.'); } self::log('Make sure created Elastic Transcoder pipeline can be read.'); $result = $this->transcoder->getCommand('ReadPipeline', array('Id' => $pipelineId))->getResult(); $this->assertEquals($pipelineName, $result->getPath('Pipeline/Name')); self::log('Delete the Elastic Transcoder pipeline.'); $response = $this->transcoder->getCommand('DeletePipeline', array('Id' => $pipelineId))->getResponse(); $this->assertEquals(202, $response->getStatusCode()); self::log('Delete the policy from the IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('DeleteRolePolicy', array('PolicyName' => $policyName, 'RoleName' => $roleName))->getResult(); self::log('Delete the IAM Role for the Elastic Transcoder pipeline.'); $result = $this->iam->getCommand('DeleteRole', array('RoleName' => $roleName))->getResult(); self::log('Delete the input and output buckets for the Elastic Transcoder pipeline.'); $commands = array(); $commands[] = $this->s3->getCommand('DeleteBucket', array('Bucket' => $inputBucket)); $commands[] = $this->s3->getCommand('DeleteBucket', array('Bucket' => $outputBucket)); $this->s3->execute($commands); }
public function testWorkingWithRoles() { $roleName = 'php-integ-iam-test-role'; self::log('Create an IAM Role.'); $result = $this->iam->getCommand('CreateRole', array('RoleName' => $roleName, 'AssumeRolePolicyDocument' => self::IAM_POLICY_ASSUME_ROLE))->getResult(); $roleArn = $result->getPath('Role/Arn'); self::log('Put a policy on the IAM Role.'); $result = $this->iam->getCommand('PutRolePolicy', array('PolicyName' => self::$policies[0], 'RoleName' => $roleName, 'PolicyDocument' => self::IAM_POLICY_ALLOW_S3))->getResult(); self::log('Put another policy on the IAM Role.'); $result = $this->iam->getCommand('PutRolePolicy', array('PolicyName' => self::$policies[1], 'RoleName' => $roleName, 'PolicyDocument' => self::IAM_POLICY_ALLOW_S3))->getResult(); self::log('make sure the IAM Role exists.'); // @TODO do a ListRoles-related assertion self::log('Make sure the policies are there.'); //print_r($this->iam->listRolePolicies(array('RoleName' => $roleName))->toArray()); $policies = $this->iam->getIterator('ListRolePolicies', array('RoleName' => $roleName)); $this->assertEquals(self::$policies, iterator_to_array($policies)); self::log('Delete the policies from the IAM Role.'); $commands = array(); foreach (self::$policies as $policy) { $commands[] = $this->iam->getCommand('DeleteRolePolicy', array('PolicyName' => $policy, 'RoleName' => $roleName)); } $this->iam->execute($commands); self::log('Delete the IAM Role.'); $result = $this->iam->getCommand('DeleteRole', array('RoleName' => $roleName))->getResult(); }
public static function assumedRoles() { $c = new IamClient(['version' => 'latest', 'region' => 'us-east-1']); $username = $c->getUser()->search('User.UserName'); $groups = $c->listGroupsForUser(['UserName' => $username])->search('Groups[].GroupName'); $policies = []; foreach ($groups as $group) { $managedPolicies = $c->ListAttachedGroupPolicies(['GroupName' => $group])->search('AttachedPolicies[].PolicyArn'); $policies = array_merge($policies, $managedPolicies); } $roles = []; foreach ($policies as $policy) { $version = $c->getPolicy(['PolicyArn' => $policy])->search('Policy.DefaultVersionId'); $policyDoc = urldecode($c->getPolicyVersion(['PolicyArn' => $policy, 'VersionId' => $version])->search('PolicyVersion.Document')); $roles = array_merge($roles, self::getAssumedRoles($policyDoc)); } return $roles; }
/** * @return User */ public function findCurrentUser() { $result = $this->iamClient->getUser(); return new User($result->get('User')); }
public function newuser() { if (empty($_POST['adminaccesskey'])) { echo json_encode(array('e' => 1, 'm' => __('You need to enter an admin access key', 'updraftplus'))); die; } if (empty($_POST['adminsecret'])) { echo json_encode(array('e' => 1, 'm' => __('You need to enter an admin secret key', 'updraftplus'))); die; } if (empty($_POST['newuser'])) { echo json_encode(array('e' => 1, 'm' => __('You need to enter a new IAM username', 'updraftplus'))); die; } if (empty($_POST['bucket'])) { echo json_encode(array('e' => 1, 'm' => __('You need to enter a bucket', 'updraftplus'))); die; } if (empty($_POST['region'])) { $_POST['region'] = 'us-east-1'; } if (empty($_POST['rrs'])) { $_POST['rrs'] = false; } $allow_download = !empty($_POST['allowdownload']) ? true : false; $allow_delete = !empty($_POST['allowdelete']) ? true : false; global $updraftplus; require_once UPDRAFTPLUS_DIR . '/methods/s3.php'; $method = new UpdraftPlus_BackupModule_s3(); $useservercerts = !empty($_POST['useservercerts']); $disableverify = !empty($_POST['disableverify']); $nossl = !empty($_POST['nossl']); $adminaccesskey = stripslashes($_POST['adminaccesskey']); $adminsecret = stripslashes($_POST['adminsecret']); $region = $_POST['region']; try { $service = $method->getS3($adminaccesskey, $adminsecret, $useservercerts, $disableverify, $nossl); if (!is_a($service, 'UpdraftPlus_S3_Compat')) { $msg = __('Cannot create new AWS user, since the old AWS toolkit is being used.', 'updraftplus'); echo json_encode(array('e' => 1, 'm' => __('Error:', 'updraftplus') . ' ' . $msg)); $updraftplus->log('Cannot create new AWS user, since the old AWS toolkit is being used.'); $updraftplus->log($msg, 'error'); return false; } } catch (AuthenticationError $e) { echo json_encode(array('e' => 1, 'm' => __('Error:', 'updraftplus') . ' ' . $e->getMessage())); $updraftplus->log('AWS authentication failed (' . $e->getMessage() . ')'); $updraftplus->log(__('AWS authentication failed', 'updraftplus') . ' (' . $e->getMessage() . ')', 'error'); return false; } catch (Exception $e) { echo json_encode(array('e' => 1, 'm' => __('Error:', 'updraftplus') . ' ' . $e->getMessage())); return false; } # Create the bucket if necessary # Get the bucket $path = stripslashes($_POST['bucket']); if (preg_match("#^/*([^/]+)/(.*)\$#", $path, $bmatches)) { $bucket = $bmatches[1]; $path = trailingslashit($bmatches[2]); } else { $bucket = $path; $path = ""; } $location = @$service->getBucketLocation($bucket); if ($location) { $bucket_exists = true; $bucket_verb = __('Region', 'updraftplus') . ": {$location}: "; } if (!isset($bucket_exists)) { $service->useDNSBucketName(true); $gb = @$service->getBucket($bucket, null, null, 1); if ($gb !== false) { $bucket_exists = true; $location = ''; $bucket_verb = ''; } } if (!isset($bucket_exists)) { $service->setExceptions(true); try { $try_to_create_bucket = @$service->putBucket($bucket, 'private', $region); } catch (Exception $e) { $try_to_create_bucket = false; $s3_error = $e->getMessage(); } $service->setExceptions(false); if ($try_to_create_bucket) { $bucket_verb = ''; $gb = $try_to_create_bucket; } else { $msg = __("Failure: We could not successfully access or create such a bucket. Please check your access credentials, and if those are correct then try another bucket name (as another AWS user may already have taken your name).", 'updraftplus'); if (isset($s3_error)) { $msg .= "\n\n" . sprintf(__('The error reported by %s was:', 'updraftplus'), 'S3') . ' ' . $s3_error; } echo json_encode(array('e' => 1, 'm' => $msg)); die; } } # Create the new IAM user require_once UPDRAFTPLUS_DIR . '/oc/autoload.php'; $credentials = array('key' => $adminaccesskey, 'secret' => $adminsecret); $iam = IamClient::factory($credentials); //Try create a new Iam user try { $response = $iam->createUser(array('Path' => '/updraftplus/', 'UserName' => $_POST['newuser'])); } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) { $response = $e->getResponse(); $code = $response->getStatusCode(); $reason = $response->getReasonPhrase(); if (403 == $code) { echo json_encode(array('e' => 1, 'm' => __('Authorisation failed (check your credentials)', 'updraftplus'))); } elseif (409 == $code && 'Conflict' == $reason) { echo json_encode(array('e' => 1, 'm' => __('Conflict: that user already exists', 'updraftplus'))); } else { echo json_encode(array('e' => 1, 'm' => sprintf(__('IAM operation failed (%s)', 'updraftplus'), 5) . " (" . $e->getMessage() . ') (' . get_class($e) . ')')); } die; } catch (Exception $e) { echo json_encode(array('e' => 1, 'm' => sprintf(__('IAM operation failed (%s)', 'updraftplus'), 4) . ' (' . $e->getMessage() . ') (' . get_class($e) . ')')); die; } if (empty($response['User']['UserId']) || empty($response['User']['CreateDate']) || empty($response['User']['UserName'])) { echo json_encode(array('e' => 1, 'm' => sprintf(__('IAM operation failed (%s)', 'updraftplus'), 3))); die; } $user = $response['User']['UserName']; $id = $response['User']['UserId']; $arn = $response['User']['Arn']; //Add the User to the bucket # Get the user API key try { $response = $iam->createAccessKey(array('UserName' => $user)); } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) { echo json_encode(array('e' => 1, 'm' => __('Failed to create user Access Key', 'updraftplus') . " (" . $e->getMessage() . ') (' . get_class($e) . ')')); die; } catch (Exception $e) { echo json_encode(array('e' => 1, 'm' => __('Operation to create user Access Key failed', 'updraftplus'))); die; } if (empty($response['AccessKey']['UserName']) || empty($response['AccessKey']['AccessKeyId']) || empty($response['AccessKey']['SecretAccessKey'])) { echo json_encode(array('e' => 1, 'm' => __('Operation to create user Access Key failed', 'updraftplus') . ' (2)')); die; } $key = $response['AccessKey']['AccessKeyId']; $secret = $response['AccessKey']['SecretAccessKey']; //policy document $pol_doc = '{ "Statement": [ { "Effect": "Allow", "Action": [ "s3:ListBucket", "s3:GetBucketLocation", "s3:ListBucketMultipartUploads" ], "Resource": "arn:aws:s3:::' . $bucket . '", "Condition": {} }, { "Effect": "Allow", "Action": [ "s3:AbortMultipartUpload",'; if ($allow_delete) { $pol_doc .= ' "s3:DeleteObject", "s3:DeleteObjectVersion",'; } if ($allow_download) { $pol_doc .= ' "s3:GetObject", "s3:GetObjectAcl", "s3:GetObjectVersion", "s3:GetObjectVersionAcl",'; } $pol_doc .= ' "s3:PutObject", "s3:PutObjectAcl", "s3:PutObjectAclVersion" ], "Resource": "arn:aws:s3:::' . $bucket . '/*", "Condition": {} }, { "Effect": "Allow", "Action": "s3:ListAllMyBuckets", "Resource": "*", "Condition": {} } ] }'; try { $response = $iam->putUserPolicy(array('UserName' => $user, 'PolicyName' => $user . 'updraftpolicy', 'PolicyDocument' => $pol_doc)); } catch (Guzzle\Http\Exception\ClientErrorResponseException $e) { echo json_encode(array('e' => 1, 'm' => __('Failed to apply User Policy', 'updraftplus') . " (" . $e->getMessage() . ') (' . get_class($e) . ')')); die; } catch (Exception $e) { echo json_encode(array('e' => 1, 'm' => __('Failed to apply User Policy' . $e->getMessage()))); die; } echo json_encode(array('e' => 0, 'u' => htmlspecialchars($user), 'k' => htmlspecialchars($key), 's' => htmlspecialchars($secret), 'l' => $region, 'c' => $bucket, 'm' => htmlspecialchars(sprintf(__("Username: %s", 'updraftplus'), $user)) . "<br>" . htmlspecialchars(sprintf(__("Access Key: %s", 'updraftplus'), $key)) . "<br>" . htmlspecialchars(sprintf(__("Secret Key: %s", 'updraftplus'), $secret)))); die; }
public function testIsGlobal() { $c = IamClient::factory(array('key' => 'foo', 'secret' => 'bar')); $this->assertEquals('https://iam.amazonaws.com', $c->getBaseUrl()); $this->assertNotNull($c->getDescription()); }