Puppet provider prefetch - ruby

I am writing a provider to generate self signed certificate using the certdog krestfield API.
I have implemented the create, destroy, exists? method and I can properly manage my certificate by making different call to the API.
I implemented puppet resource using the self.prefetch and self.instances methods. I can retrieve the properties of my resources to be aware of their current state.
My resource contain two sensitive types 'username' and 'password' who are required to make the API calls. I can't store those values on the filesystem and I want the 'puppet resource' command to ignore those types.
Currently when I run 'puppet apply' for the manifest:
certdog_certificate { 'tstpuppet':
ensure => present,
server => 'apiserver',
username => 'apiserver_username',
password => 'apiserver_password',
}
It returns:
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/username: defined 'username' as 'apiserver_username'
Notice: /Stage[main]/Main/Certdog_certificate[tstpuppet]/password: defined 'password' as 'apiserver_password'
Is there a way to hide sensitive types for puppet resources ? How should I process ?

I had to properly define my resource attributes.
The configurable data not part of the persistant state should be parameters as describe in the puppet documentation.
The attributes username and password are now define with newparam instead of newproperty as below.
module Puppet
Type.newtype(:certdog_certificate) do
#doc = 'Manage certificate using certdog REST API'
ensurable do
desc 'Create or remove a certificate'
newvalue(:present) do
provider.create
end
newvalue(:absent) do
provider.destroy
end
defaultto :present
end
newparam(:cert_name, namevar: true) do
desc 'Name of the certificate request'
end
newparam(:username) do
desc 'Username for Certdog API server'
end
newparam(:password) do
desc 'Password for Certdog API server'
end
newproperty(:server) do
desc 'Certdog API server address'
end
end
#john-bollinger Thanks for your explanation, I was missing an important concept of the custom types.

Related

where the 'attr' value of the validate of SocialLoginSerializer is output in django rest framework

I wonder where the attrs of validate in drf's SocialLoginSerializer are expressed.
Actually, I want to change the response values ​​when I do social login,
but I don't know where to change them.
Please help me
class SocialLoginSerializer(serializers.Serializer):
...
def validate(self, attrs):
...
if not login.is_existing:
# We have an account already signed up in a different flow
# with the same email address: raise an exception.
# This needs to be handled in the frontend. We can not just
# link up the accounts due to security constraints
if allauth_settings.UNIQUE_EMAIL:
# Do we have an account already with this email address?
account_exists = get_user_model().objects.filter(
email=login.user.email,
).exists()
if account_exists:
raise serializers.ValidationError(
_('User is already registered with this e-mail address.'),
)
login.lookup()
login.save(request, connect=True)
return attrs

How to search roles in ldap recursively with Net::LDAP in Ruby

I'm creating a self service with the possibility to grant application roles (defined in a meta [ldap]) for a user. Our structure in the meta is not uniform. It looks like this:
o=meta
ou=Firm
ou=AppRoles
ou=GitLab
cn=Admin
cn=User
ou=SAP
ou=SAPCRT
cn=Admin
cn=User
ou=SAPLST
ou=NW
cn=Admin
cn=User
ou=ST
cn=Admin
cn=User
etc...
So you see, the cn (Approle) is not always on the same level.
This is the code I have so far. It finds 'ou's like GitLab Admin and GitLab User. But I need to receive a list with Gitlab Admin, Gitlab User, SAP/SAPCRT Admin, SAP/SAPCRT User, SAP/SAPLST/NW Admin, and so forth.
base = 'ou=AppRoles,ou=Firm,o=META'
filter = Net::LDAP::Filter.begins('ou', query)
How can I setup Net::LDAP to filter/search recursively?
Not sure if this will print all cn's under AppRole, but with the "puts" command you will see the output, could you show us the return of this block of code?
def get_ldap_users(ldap_password)
filter = Net::LDAP::Filter.eq("ou", "AppRoles")
treebase = "dc=yourdomainhere"
get_ldap(ldap_password).search(:base => treebase, :filter => filter) do |entry|
puts "CN: #{entry.cn}"
end
end

How to connect to mongo, using ruby that have credentials?

I am trying to connect to a database that has credentials. I cannot find any useful information online...
require: 'mongo'
begin
db = Mongo::Connection.new(" IP ADDRESS " , PORT ).db("COLLECTION")
db.authenticate("username","password")
rescue StandardError => err
abort("error")
end
C:/Ruby193/lib/ruby/gems/1.9.1/gems/mongo-1.8.2/lib/mongo/networking.rb:306:in `rescue in receive_message_on_socket': Operation failed with the following exception: end of file reached (Mongo::ConnectionFailure)
looks like there is an #add_auth method as well as auths can be passed to the constructor maybe try
auths = [{"db_name" => "COLLECTION",
"username" => YOUR_USERNAME,
"password" => YOUR_PASSWORD}]
Mongo::Connection.new(" IP ADDRESS " , PORT, auths: auths)
OR
auth = {"db_name" => "COLLECTION",
"username" => YOUR_USERNAME,
"password" => YOUR_PASSWORD}
Mongo::Connection.new(" IP ADDRESS " , PORT).add_auth(auth)
and see if that works
Reference Mongo::MongoClient::GENERIC_OPTS and Mongo::MongoClient#setup
BTW that is a old version of the gem and ruby for that matter. have you considered the possibly upgrading?
Newest version (as of now) of Mongo is 2.4.3 and the options are more transparent now e.g.
Mongo::Client.new("IP_ADDRESS:PORT", user: USERNAME, password: PASSWORD, auth_mech: AUTHENTICATION_MECHANISM)
Although based on your comments I am not sure authentication is your issue

Ruby hipchat gem invalid send file

So this is related to an earlier post I made on this method. This is essentially what I am using to send files via hipchat:
#!/usr/bin/env ruby
require 'hipchat'
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'HIPCHAT_URL')
client.user('some_username').send_file('message', File.open('./output/some-file.csv') )
client['some_hipchat_room'].send_file('some_user', 'message', File.open('./output/some-file.csv') )
Now for some reason the send_file method is invalid:
/path/to/gems/hipchat-1.5.4/lib/hipchat/errors.rb:40:in `response_code_to_exception_for': You requested an invalid method. path:https://hipchat.illum.io/v2/user/myuser#myemail/share/file?auth_token=asdfgibberishasdf method:Net::HTTP::Get (HipChat::MethodNotAllowed)
from /path/to/gems/gems/hipchat-1.5.4/lib/hipchat/user.rb:50:in `send_file'
I think this indicating that you should be using POST instead of GET, but I'm not sure because I haven't used this library nor Hipchat.
Looking at the question you referenced and the source posted by another user they're sending the request using self.class.post, and your debug output shows Net::HTTP::Get
To debug, could you try,
file = Tempfile.new('foo').tap do |f|
f.write("the content")
f.rewind
end
user = client.user(some_username)
user.send_file('some bytes', file)
The issue is that I was attempting to connect to the server via http instead of https. If the following client is causing issues:
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'my.company.com')
Then try adding https:// to the beginning of your company's name.
client = HipChat::Client.new('HIPCHAT_TOKEN', :api_version => 'v2', :server_url => 'https://my.company.com')

Generating Paypal Signature, 'X-PAYPAL-AUTHORIZATION' in Ruby

Is there any library in Ruby that generates the Signature, 'X-PAYPAL-AUTHORIZATION' header that is required to make calls on behalf of the account holder who has authorized us through the paypal Permissions API.
I am done with the permissions flow and get the required access token, tokenSecret. I feel I am generating the signature incorrectly as all my calls with the the generated 'X-PAYPAL-AUTHORIZATION' fail. They give the following errors:
For NVP call I get:
You do not have permissions to make this API call
And for the GetBasicPersonalData call I get:
Authentication failed. API credentials are incorrect.
Has anyone gone through this in Ruby? What is best way to generate signature. Paypal has just provided some SDK in Paypal, Java, but not the algorithm to generate signature.
Thanks,
Nilesh
Take a look at the PayPal Permissions gem.
https://github.com/moshbit/paypal_permissions
Specifically lib/paypal_permissions/x_pp_authorization.rb
require 'cgi'
require 'openssl'
require 'base64'
class Hash
def to_paypal_permissions_query
collect do |key, value|
"#{key}=#{value}"
end.sort * '&'
end
end
module ActiveMerchant #:nodoc:
module Billing #:nodoc:
module XPPAuthorization
public
def x_pp_authorization_header url, api_user_id, api_password, access_token, access_token_verifier
timestamp = Time.now.to_i.to_s
signature = x_pp_authorization_signature url, api_user_id, api_password, timestamp, access_token, access_token_verifier
{ 'X-PAYPAL-AUTHORIZATION' => "token=#{access_token},signature=#{signature},timestamp=#{timestamp}" }
end
public
def x_pp_authorization_signature url, api_user_id, api_password, timestamp, access_token, access_token_verifier
# no query params, but if there were, this is where they'd go
query_params = {}
key = [
paypal_encode(api_password),
paypal_encode(access_token_verifier),
].join("&")
params = query_params.dup.merge({
"oauth_consumer_key" => api_user_id,
"oauth_version" => "1.0",
"oauth_signature_method" => "HMAC-SHA1",
"oauth_token" => access_token,
"oauth_timestamp" => timestamp,
})
sorted_query_string = params.to_paypal_permissions_query
base = [
"POST",
paypal_encode(url),
paypal_encode(sorted_query_string)
].join("&")
base = base.gsub /%([0-9A-F])([0-9A-F])/ do
"%#{$1.downcase}#{$2.downcase}" # hack to match PayPal Java SDK bit for bit
end
digest = OpenSSL::HMAC.digest('sha1', key, base)
Base64.encode64(digest).chomp
end
# The PayPalURLEncoder java class percent encodes everything other than 'a-zA-Z0-9 _'.
# Then it converts ' ' to '+'.
# Ruby's CGI.encode takes care of the ' ' and '*' to satisfy PayPal
# (but beware, URI.encode percent encodes spaces, and does nothing with '*').
# Finally, CGI.encode does not encode '.-', which we need to do here.
def paypal_encode str
s = str.dup
CGI.escape(s).gsub('.', '%2E').gsub('-', '%2D')
end
end
end
end
Sample parameters:
url = 'https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData'
api_user_id = 'caller_1234567890_biz_api1.yourdomain.com'
api_password = '1234567890'
access_token = 'YJGjMOmTUqVPlKOd1234567890-jdQV3eWCOLuCQOyDK1234567890'
access_token_verifier = 'PgUjnwsMhuuUuZlPU1234567890'
The X-PAYPAL-AUTHORIZATION header [is] generated with URL "https://svcs.paypal.com/Permissions/GetBasicPersonalData". (see page 23, and chapter 7, at the link)
NVP stating "You do not have permissions to make this API call" means your API credentials are correct, just that your account does not have permission for the particular API you are trying to call. Something between the two calls you are submitting is not using the same API credentials.
For NVP call I get:
What NVP call?
TransactionSearch (see comments below)
Also, if you haven't already done so, you will want to use the sandbox APP-ID for testing in the sandbox, and you will need to apply for an app-id with Developer Technical Services (DTS) at PayPal to get an App-ID for live.
EDIT:
To use the TransactionSearch API, all you should be submitting is below. You do not need to specify any extra headers.
USER=xxxxxxxxxxxxxxxxxx
PWD=xxxxxxxxxxxxxxxxxx
SIGNATURE=xxxxxxxxxxxxxxxxxx
METHOD=TransactionSearch
VERSION=86.0
STARTDATE=2009-10-11T00:00:00Z
TRANSACTIONID=1234567890
//And for submitting API calls on bob's behalf, if his PayPal email was bob#bob.com:
SUBJECT=bob#bob.com

Resources