1
0
Fork 0
mirror of https://github.com/fog/fog-aws.git synced 2022-11-09 13:50:52 -05:00

Merge pull request #339 from engineyard/better-iam-policies

Better iam policies
This commit is contained in:
Josh Lane 2017-01-20 10:15:40 -08:00 committed by GitHub
commit 2d7e4719e3
29 changed files with 472 additions and 26 deletions

View file

@ -99,6 +99,8 @@ module Fog
collection :access_keys
model :group
collection :groups
model :instance_profile
collection :instance_profiles
model :managed_policy
collection :managed_policies
model :policy
@ -117,6 +119,7 @@ module Fog
hash[key] = {
:owner_id => owner_id,
:instance_profiles => {},
:server_certificates => {},
:access_keys => [{
"Status" => "Active",

View file

@ -2561,6 +2561,7 @@
"Effect": "Allow",
"Action": [
"iam:GenerateCredentialReport",
"iam:GenerateServiceLastAccessedDetails",
"iam:Get*",
"iam:List*"
],

View file

@ -0,0 +1,40 @@
module Fog
module AWS
class IAM
class InstanceProfile < Fog::Model
identity :name, :aliases => 'InstanceProfileName'
attribute :id, :aliases => 'InstanceProfileId'
attribute :roles, :aliases => 'Roles', :type => :array
attribute :arn, :aliases => 'Arn'
attribute :path, :aliases => 'Path'
attribute :create_date, :aliases => 'CreateDate', :type => :time
def add_role(role_name)
requires :identity
service.add_role_to_instance_profile(role_name, self.name)
true
end
def remove_role(role_name)
requires :identity
service.remove_role_from_instance_profile(role_name, self.name)
true
end
def destroy
requires :identity
service.delete_instance_profile(self.identity)
true
end
def save
requires :identity
data = service.create_instance_profile(self.name, self.path).body['InstanceProfile']
merge_attributes(data)
end
end
end
end
end

View file

@ -0,0 +1,24 @@
require 'fog/aws/models/iam/instance_profile'
module Fog
module AWS
class IAM
class InstanceProfiles < Fog::AWS::IAM::PagedCollection
model Fog::AWS::IAM::InstanceProfile
def all(options={})
body = service.list_instance_profiles(page_params(options)).body
merge_attributes(body)
load(body["InstanceProfiles"])
end
def get(identity)
new(service.get_instance_profile(identity).body["Role"])
rescue Excon::Errors::NotFound, Fog::AWS::IAM::NotFound
nil
end
end
end
end
end

View file

@ -8,6 +8,7 @@ module Fog
attribute :username
attribute :group_name
attribute :role_name
model Fog::AWS::IAM::ManagedPolicy
@ -16,6 +17,8 @@ module Fog
all_by_user(self.username, options)
elsif self.group_name
all_by_group(self.group_name, options)
elsif self.role_name
all_by_role(self.role_name, options)
else
all_policies(options)
end
@ -51,6 +54,15 @@ module Fog
end
end
def all_by_role(role_name, options={})
body = service.list_attached_role_policies(role_name, page_params(options)).body
merge_attributes(body)
body['Policies'].map do |policy|
service.get_policy(policy['PolicyArn']).body['Policy']
end
end
def all_policies(options={})
body = service.list_policies(page_params(options)).body
merge_attributes(body)

View file

@ -14,6 +14,8 @@ module Fog
attribute :path, :aliases => 'Path'
attribute :updated_at, :aliases => 'UpdateDate', :type => :time
attr_accessor :policy_document
def attach(user_or_username)
requires :arn
@ -32,6 +34,24 @@ module Fog
service.get_policy_version(self.arn, self.default_version).
body['PolicyVersion']['Document']
end
def reload
service.managed_policies.get(self.arn)
end
def save
requires :name, :policy_document
merge_attributes(service.create_policy(self.name, self.policy_document, self.path, self.description).body["Policy"])
end
def destroy
requires :arn
service.delete_policy(self.arn)
true
end
end
end
end

View file

@ -20,6 +20,41 @@ module Fog
true
end
def attach(policy_or_arn)
requires :rolename
arn = if policy_or_arn.respond_to?(:arn)
policy_or_arn.arn
else
policy_or_arn
end
service.attach_role_policy(self.rolename, arn)
end
def detach(policy_or_arn)
requires :rolename
arn = if policy_or_arn.respond_to?(:arn)
policy_or_arn.arn
else
policy_or_arn
end
service.detach_role_policy(self.rolename, arn)
end
def attached_policies
requires :rolename
service.managed_policies(:role_name => self.rolename)
end
def instance_profiles
requires :rolename
service.instance_profiles.load(service.list_instance_profiles_for_role(self.rolename).body["InstanceProfiles"])
end
def destroy
requires :rolename

View file

@ -27,6 +27,25 @@ module Fog
)
end
end
class Mock
def add_role_to_instance_profile(role_name, instance_profile_name)
response = Excon::Response.new
unless profile = self.data[:instance_profiles][instance_profile_name]
raise Fog::AWS::IAM::NotFound.new("Instance Profile #{instance_profile_name} cannot be found.")
end
unless role = self.data[:roles][role_name]
raise Fog::AWS::IAM::NotFound.new("Role #{role_name} cannot be found.")
end
profile["Roles"] << role_name
response.body = {"RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -46,6 +46,7 @@ module Fog
group = self.data[:groups][group_name]
group[:attached_policies] << policy_arn
managed_policy["AttachmentCount"] += 1
Excon::Response.new.tap { |response|
response.status = 200

View file

@ -20,13 +20,39 @@ module Fog
#
def attach_role_policy(role_name, policy_arn)
request(
'Action' => 'AttachRolePolicy',
'RoleName' => role_name,
'PolicyArn' => policy_arn,
:parser => Fog::Parsers::AWS::IAM::Basic.new
'Action' => 'AttachRolePolicy',
'RoleName' => role_name,
'PolicyArn' => policy_arn,
:parser => Fog::Parsers::AWS::IAM::Basic.new
)
end
end
class Mock
def attach_role_policy(role_name, policy_arn)
response = Excon::Response.new
if policy_arn.nil?
raise Fog::AWS::IAM::ValidationError, "1 validation error detected: Value null at 'policyArn' failed to satisfy constraint: Member must not be null"
end
managed_policy = self.data[:managed_policies][policy_arn]
unless managed_policy
raise Fog::AWS::IAM::NotFound, "Policy #{policy_arn} does not exist."
end
unless self.data[:roles][role_name]
raise Fog::AWS::IAM::NotFound.new("The role with name #{role_name} cannot be found.")
end
role = self.data[:roles][role_name]
role[:attached_policies] ||= []
role[:attached_policies] << managed_policy['Arn']
managed_policy['AttachmentCount'] += 1
response.body = {"RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -46,6 +46,7 @@ module Fog
user = self.data[:users][user_name]
user[:attached_policies] << policy_arn
managed_policy['AttachmentCount'] += 1
Excon::Response.new.tap { |response|
response.status = 200

View file

@ -40,6 +40,26 @@ module Fog
}.merge!(options))
end
end
class Mock
def create_instance_profile(instance_profile_name, path='/', options={})
response = Excon::Response.new
profile = {
"Arn" => "arn:aws:iam::#{Fog::AWS::Mock.owner_id}:instance-profile#{path}#{instance_profile_name}",
"CreateDate" => Time.now.utc,
"InstanceProfileId" => Fog::Mock.random_hex(21),
"InstanceProfileName" => instance_profile_name,
"Path" => path,
"Roles" => [],
}
self.data[:instance_profiles][instance_profile_name] = profile
response.body = {"InstanceProfile" => profile, "RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -35,13 +35,37 @@ module Fog
'PolicyName' => policy_name,
'PolicyDocument' => Fog::JSON.encode(policy_document),
'Path' => path,
'Description' => description,
'Description' => description,
:parser => Fog::Parsers::AWS::IAM::SinglePolicy.new
}.reject {|_, value| value.nil?})
end
end
class Mock
def create_policy(policy_name, policy_document, path="/", description=nil)
response = Excon::Response.new
arn = "arn:aws:iam:#{Fog::AWS::Mock.owner_id}:policy/#{policy_name}"
policy = {
"Arn" => arn,
"AttachmentCount" => 0,
"CreateDate" => Time.now.utc,
"DefaultVersionId" => "v1",
"Description" => description,
"IsAttachable" => true,
"Path" => path,
"PolicyId" => Fog::Mock.random_hex(21),
"PolicyName" => policy_name,
"UpdateDate" => Time.now.utc,
}
self.data[:managed_policies][arn] = policy
response.body = {"RequestId" => Fog::AWS::Mock.request_id, "Policy" => policy}
response
end
end
end
end
end

View file

@ -25,6 +25,21 @@ module Fog
)
end
end
class Mock
def delete_instance_profile(instance_profile_name)
response = Excon::Response.new
unless profile = self.data[:instance_profiles][instance_profile_name]
raise Fog::AWS::IAM::NotFound.new("Instance Profile #{instance_profile_name} cannot be found.")
end
self.data[:instance_profiles].delete(instance_profile_name)
response.body = {"RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -25,6 +25,21 @@ module Fog
)
end
end
class Mock
def delete_policy(policy_arn)
response = Excon::Response.new
policy = self.data[:managed_policies][policy_arn]
if policy.nil?
raise Fog::AWS::IAM::NotFound.new("Policy #{policy_arn} does not exist or is not attachable.")
end
self.data[:managed_policies].delete(policy_arn)
response.body = {"RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -46,6 +46,7 @@ module Fog
group = self.data[:groups][group_name]
group[:attached_policies].delete(policy_arn)
managed_policy["AttachmentCount"] -= 1
Excon::Response.new.tap { |response|
response.status = 200

View file

@ -27,6 +27,33 @@ module Fog
)
end
end
class Mock
def detach_role_policy(role_name, policy_arn)
response = Excon::Response.new
if policy_arn.nil?
raise Fog::AWS::IAM::ValidationError, "1 validation error detected: Value null at 'policyArn' failed to satisfy constraint: Member must not be null"
end
managed_policy = self.data[:managed_policies][policy_arn]
unless managed_policy
raise Fog::AWS::IAM::NotFound, "Policy #{policy_arn} does not exist."
end
unless self.data[:roles].key?(role_name)
raise Fog::AWS::IAM::NotFound.new("The role with name #{role_name} cannot be found.")
end
role = self.data[:roles][role_name]
role[:attached_policies].delete(policy_arn)
managed_policy["AttachmentCount"] -= 1
response.body = {"RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -46,6 +46,7 @@ module Fog
user = self.data[:users][user_name]
user[:attached_policies].delete(policy_arn)
managed_policy["AttachmentCount"] -= 1
Excon::Response.new.tap { |response|
response.status = 200

View file

@ -35,6 +35,23 @@ module Fog
})
end
end
class Mock
def get_instance_profile(instance_profile_name)
response = Excon::Response.new
instance_profile = self.data[:instance_profiles][instance_profile_name]
unless instance_profile
raise Fog::AWS::IAM::NotFound.new("Instance Profile #{instance_profile_name} cannot be found.")
end
instance_profile = instance_profile.dup
instance_profile["Roles"].map! { |r| self.data[:roles][r] }
response.body = {"InstanceProfile" => instance_profile, "RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -70,7 +70,8 @@ module Fog
body = {
'Policies' => data,
'IsTruncated' => truncated,
'RequestId' => Fog::AWS::Mock.request_id
'RequestId' => Fog::AWS::Mock.request_id,
'Marker' => nil
}
if marker

View file

@ -43,6 +43,15 @@ module Fog
}.merge!(options))
end
end
class Mock
def list_instance_profiles(options={})
response = Excon::Response.new
profiles = self.data[:instance_profiles].values
response.body = { "InstanceProfiles" => profiles, "IsTruncated" => false, "RequestId" => Fog::AWS::Mock.request_id }
response
end
end
end
end
end

View file

@ -44,6 +44,16 @@ module Fog
}.merge!(options))
end
end
class Mock
def list_instance_profiles_for_role(role_name, options={})
response = Excon::Response.new
profiles = self.data[:instance_profiles].values.select { |p| p["Roles"].include?(role_name) }
response.body = { "InstanceProfiles" => profiles, "IsTruncated" => false, "RequestId" => Fog::AWS::Mock.request_id }
response
end
end
end
end
end

View file

@ -64,6 +64,10 @@ module Fog
self.data[:managed_policies].values
end
if options["PathPrefix"]
data_set = data_set.select { |p| p["Path"].match(/^#{options["PathPrefix"]}/) }
end
data = data_set.slice!(0, limit || 100)
truncated = data_set.size > 0
marker = truncated && Base64.encode64("metadata/l/#{account_id}/#{UUID.uuid}")

View file

@ -28,6 +28,25 @@ module Fog
)
end
end
class Mock
def remove_role_from_instance_profile(role_name, instance_profile_name)
response = Excon::Response.new
unless profile = self.data[:instance_profiles][instance_profile_name]
raise Fog::AWS::IAM::NotFound.new("Instance Profile #{instance_profile_name} cannot be found.")
end
unless role = self.data[:roles][role_name]
raise Fog::AWS::IAM::NotFound.new("Role #{role_name} cannot be found.")
end
profile["Roles"].delete(role_name)
response.body = {"RequestId" => Fog::AWS::Mock.request_id}
response
end
end
end
end
end

View file

@ -0,0 +1,18 @@
Shindo.tests("Fog::AWS[:iam] | instance_profiles", ['aws', 'iam']) do
model_tests(Fog::AWS[:iam].instance_profiles, {:name => uniq_id('fog-instance-profile')}) do
@role = Fog::AWS[:iam].roles.create(:rolename => uniq_id('fog-role'))
tests("#add_role('#{@role.rolename}')") do
returns(true) { @instance.add_role(@role.rolename) }
end
returns(1) { @role.instance_profiles.count }
returns(@instance) { @role.instance_profiles.first }
tests("#remove_role('#{@role.rolename}')") do
returns(true) { @instance.remove_role(@role.rolename) }
end
@role.destroy
end
end

View file

@ -22,7 +22,7 @@ Shindo.tests("Fog::Compute[:iam] | managed_policies", ['aws','iam']) do
"Statement" => [
{
"Effect" => "Allow",
"Action" => [ "iam:GenerateCredentialReport", "iam:Get*", "iam:List*" ],
"Action" => [ "iam:GenerateCredentialReport", "iam:GenerateServiceLastAccessedDetails", "iam:Get*", "iam:List*" ],
"Resource" => "*"
}
]
@ -38,6 +38,8 @@ Shindo.tests("Fog::Compute[:iam] | managed_policies", ['aws','iam']) do
user.attached_policies.map(&:identity) == [policy.identity]
end
returns(1) { policy.reload.attachments}
tests("#detach").succeeds do
user.detach(policy)
@ -56,6 +58,8 @@ Shindo.tests("Fog::Compute[:iam] | managed_policies", ['aws','iam']) do
group.attached_policies.map(&:identity) == [policy.identity]
end
returns(1) { policy.reload.attachments}
tests("#detach").succeeds do
group.detach(policy)
@ -64,4 +68,22 @@ Shindo.tests("Fog::Compute[:iam] | managed_policies", ['aws','iam']) do
group.destroy
end
tests("roles") do
role = iam.roles.create(:rolename => uniq_id("fog-test-role"))
tests("#attach").succeeds do
role.attach(policy)
role.attached_policies.map(&:identity) == [policy.identity]
end
returns(1) { policy.reload.attachments}
tests("#detach").succeeds do
role.detach(policy)
role.attached_policies.map(&:identity) == []
end
role.destroy
end
end

View file

@ -131,6 +131,24 @@ Xb9WSr07saxZQbxBPQyTlb0Q9Tu2djAq2/o/nYD1/50/fXUTuWMB
}],
'IsTruncated' => Fog::Boolean
)
INSTANCE_PROFILE = {
'Arn' => String,
'CreateDate' => Time,
'InstanceProfileId' => String,
'InstanceProfileName' => String,
'Path' => String,
'Roles' => Array
}
INSTANCE_PROFILE_RESULT = BASIC.merge(
'InstanceProfile' => INSTANCE_PROFILE
)
LIST_INSTANCE_PROFILE_RESULT = BASIC.merge(
"IsTruncated" => Fog::Boolean,
"InstanceProfiles" => [INSTANCE_PROFILE]
)
end
end
end

View file

@ -0,0 +1,44 @@
include AWS::IAM::Formats
Shindo.tests("AWS::IAM | instance profile requests", ['aws']) do
tests('success') do
profile_name = uniq_id('fog-instance-profile')
@instance_profile_count = Fog::AWS[:iam].list_instance_profiles.body["InstanceProfiles"].count
tests("#create_instance_profile('#{profile_name}')").formats(INSTANCE_PROFILE_RESULT) do
Fog::AWS[:iam].create_instance_profile(profile_name).body
end
tests("#list_instance_profiles").formats(LIST_INSTANCE_PROFILE_RESULT) do
body = Fog::AWS[:iam].list_instance_profiles.body
returns(@instance_profile_count + 1) { body["InstanceProfiles"].count }
body
end
tests("#get_instance_profile('#{profile_name}')").formats(INSTANCE_PROFILE_RESULT) do
Fog::AWS[:iam].get_instance_profile(profile_name).body
end
@role = Fog::AWS[:iam].roles.create(:rolename => uniq_id('instance-profile-role'))
tests("#add_role_to_instance_profile('#{@role.rolename}', '#{profile_name}')").formats(BASIC) do
Fog::AWS[:iam].add_role_to_instance_profile(@role.rolename, profile_name).body
end
tests("#list_instance_profiles_for_role('#{@role.rolename}')").formats(LIST_INSTANCE_PROFILE_RESULT) do
body = Fog::AWS[:iam].list_instance_profiles_for_role(@role.rolename).body
returns(1) { body["InstanceProfiles"].count }
body
end
tests("#remove_role_from_instance_profile('#{@role.rolename}', '#{profile_name}')").formats(BASIC) do
Fog::AWS[:iam].remove_role_from_instance_profile(@role.rolename, profile_name).body
end
@role.destroy
tests("#delete_instance_profile('#{profile_name}')").formats(BASIC) do
Fog::AWS[:iam].delete_instance_profile(profile_name).body
end
end
end

View file

@ -1,6 +1,5 @@
Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
pending if Fog.mocking?
Fog::AWS[:iam].create_group('fog_policy_test_group')
Fog::AWS[:iam].create_user('fog_policy_test_user')
Fog::AWS[:iam].create_role('fog_policy_test_role', Fog::AWS::IAM::EC2_ASSUME_ROLE_POLICY)
@ -8,16 +7,16 @@ Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
tests('success') do
@policy = {'Version' => '2012-10-17', "Statement" => [{"Effect" => "Deny", "Action" => "*", "Resource" => "*"}]}
@policy_format = {
'Arn' => String,
'AttachmentCount' => Integer,
'Description' => String,
'Arn' => String,
'AttachmentCount' => Integer,
'Description' => Fog::Nullable::String,
'DefaultVersionId' => String,
'IsAttachable' => Fog::Boolean,
'Path' => String,
'PolicyId' => String,
'PolicyName' => String,
'CreateDate' => Time,
'UpdateDate' => Time
'IsAttachable' => Fog::Boolean,
'Path' => String,
'PolicyId' => String,
'PolicyName' => String,
'CreateDate' => Time,
'UpdateDate' => Time
}
create_policy_format = {
@ -28,8 +27,8 @@ Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
list_policies_format = {
'RequestId' => String,
'Policies' => [@policy_format],
'Marker' => String,
'IsTruncated' => Fog::Boolean
'Marker' => Fog::Nullable::String,
'IsTruncated' => Fog::Boolean
}
attached_policy_format = {
@ -39,7 +38,7 @@ Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
list_managed_policies_format = {
'RequestId' => String,
'AttachedPolicies' => [attached_policy_format]
'Policies' => [attached_policy_format]
}
tests("#create_policy('fog_policy')").formats(create_policy_format) do
@ -74,7 +73,7 @@ Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
Fog::AWS[:iam].attach_group_policy('fog_policy_test_group', @policy_arn).body
end
tests("#list_attach_group_policies()").formats(fog_policy_test_group) do
tests("#list_attach_group_policies()").formats(list_managed_policies_format) do
Fog::AWS[:iam].list_attached_group_policies('fog_policy_test_group').body
end
@ -83,11 +82,11 @@ Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
end
tests("#attach_role_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].attach_role_policy('fog_policy_test_role', @policy_arn).body
body = Fog::AWS[:iam].attach_role_policy('fog_policy_test_role', @policy_arn).body
end
tests("#list_attach_role_policies()").formats(fog_policy_test_group) do
Fog::AWS[:iam].attach_role_policies('fog_policy_test_role').body
tests("#list_attached_role_policies()").formats(list_managed_policies_format) do
Fog::AWS[:iam].list_attached_role_policies('fog_policy_test_role').body
end
tests("#detach_role_policy()").formats(AWS::IAM::Formats::BASIC) do
@ -97,7 +96,7 @@ Shindo.tests('AWS::IAM | managed policy requests', ['aws']) do
tests("#delete_policy()").formats(AWS::IAM::Formats::BASIC) do
Fog::AWS[:iam].delete_policy(@policy_arn).body
end
end
tests('failure') do