How can I decode the base64 payload from Google Secret Manager? - google-secret-manager

When using secret manager, the response is base64 encoded. How would one go about decoding it?
sendGridSend:
steps:
- getSecret:
call: http.get
args:
url: ${"https://secretmanager.googleapis.com/v1/projects/" + sys.get_env("GOOGLE_CLOUD_PROJECT_NUMBER") + "/secrets/" + secret + "/versions/latest:access"}
auth:
type: OAuth2
result: secretBase64Payload

It would be like the below snippet, by using base64.decode.
As this product just got out of alpha, there is no yet a documentation page linking to the available functions.
sendGridSend:
params: [secret, from, to, subject, content, contentType]
steps:
- getSecret:
call: http.get
args:
url: ${"https://secretmanager.googleapis.com/v1/projects/" + sys.get_env("GOOGLE_CLOUD_PROJECT_NUMBER") + "/secrets/" + secret + "/versions/latest:access"}
auth:
type: OAuth2
result: sendGridKey
- decodeSecrets:
assign:
- decodedKey: ${text.decode(base64.decode(sendGridKey.body.payload.data))}

Related

How to get access token from Azure Active Directory with certificate when service is behind proxy

I need to create service that calls graph api to access company data. In order to authenticate I need JWT token from Azure Active Directory. The authentication will be using application mode with signing certificate. I tried to use MSAL node ConfidentialClientApplication but the service needs to use http proxy to connect to internet. To my knowledge MSAL node does not support this and calls result in library being unable to resolve the address of "https://login.microsoftonline.com". How can I make MSAL node use the proxy or get JWT token without use od MSAL?
In order to get JWT token from azure active directory without MSAL node, one have to generate proper JWT token on its own and then sign it with certificate private key. The header of the token consists of following fields:
{
typ: "JWT",
alg: "RS256",
kid: "156E...",
x5t: "iTYVn..."
}
"kid" is the thumbprint of the certificate used to sign the request - here is a good example how to obtain it for pfx file with powershell https://stackoverflow.com/a/32980899/3588432
"x5t" is base64 encoded and sanitized certificate thumbprint.
Sanitization of base64 encoded string means:
trimming "=" signs at the end
replace "/" with "_"
replace "+" with "-"
Exemplary C# code for the sanitization:
var sanitized = s.Split('=')[0].Replace('+', '-').Replace('/', '_');
and JS code:
var sanitized = s.split('=')[0].replace('+', '-').replace('/', '_');
The payload of the token consists of the following fields:
{
aud: "https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token",
iss: "{clientId}",
nbf: 1617952610,
exp: 1617953210,
sub: "{clientId}",
jti: "e13efcf..."
}
{tenantId} and {clientId} are Azure AD data of application we are authenticating to
"nbf" is the time when the token will began to be valid, normally it is time the token got generated. It has unix epoch format https://en.wikipedia.org/wiki/Unix_time and is an integer.
"exp" - the time the token expires in unix epoch format.
"jti" - a unique token identifier. It may be random generated guid. Should be different for every request.
An example how to get "nbf" value in JavaScript:
var nbf = Math.floor(new Date().getTime() / 1000);
When ready header and payload should be serialized (with sanitization) on concatenated with ".":
var token = JSON.stringify(header) + "." + JSON.stringify(payload);
Then we need to sign it with certificate private key, encode it with base 64 (with sanitization) and prepare a clientAssertion value:
var clientAssertion = token + "." + signedToken;
As a last step can send request to get JWT token:
const body = new URLSearchParams();
const token = await fetch("https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token", {
agent: new HttpsProxyAgent("http://..."),
body: new URLSearchParams({
"client_assertion": clientAssertion,
"client_id": "{clientId}",
"scope": "https://graph.microsoft.com/.default"
"client_assertion_type": "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"
"grant_type": "client_credentials"
}),
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded"
}
})
.then(response => response.json().access_token);

How to use client secret having special characters in groovy

I am trying to run Microsoft graph API to generate token. This is working fine in postman but failed in SoapUI. I think client secret has special characters which are causing the issue.
client secret:
osi5oX-:?0A3YiG4aCpZ.Y[+PW51pZVY
API URL (POST) :
https://login.microsoftonline.com/{tenantID}/oauth2/v2.0/token
Body:
client_id=xxxxx&client_secret=osi5oX-:?0A3YiG4aCpZ.Y[+PW51pZVY&grant_type=client_credentials&scope=https://graph.microsoft.com/.default
Error:
{"error":"invalid_client","error_description":"AADSTS7000215: Invalid client secret is provided.\r\nTrace ID: 32b5bf83-f908-4b4e-9fe6-5b05fd949e00\r\nCorrelation ID: b9b7ce92-f5d1-41d1-8d92-eed8a6a5470b\r\nTimestamp: 2020-05-07 17:27:08Z","error_codes":[7000215],"timestamp":"2020-05-07 17:27:08Z","trace_id":"32b5bf83-f908-4b4e-9fe6-5b05fd949e00","correlation_id":"b9b7ce92-f5d1-41d1-8d92-eed8a6a5470b","error_uri":"https://login.microsoftonline.com/error?code=7000215"}
Use secret after encoding and it works.
import java.net.URLEncoder;
String url = "osi5oX-:?0A3YiG4aCpZ.Y[+PW51pZVY"
String encodedUrl = URLEncoder.encode(url, "UTF-8" );
println(encodedUrl)​

Google sign integration not working

I followed this guide to integrate google sign in: https://developers.google.com/identity/sign-in/web/
But when I click the sign in button a pop up comes and goes but doesn't provide any information of the user.
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId()); // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName());
console.log('Given Name: ' + profile.getGivenName());
console.log('Family Name: ' + profile.getFamilyName());
console.log("Image URL: " + profile.getImageUrl());
console.log("Email: " + profile.getEmail());
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token;
console.log("ID Token: " + id_token);
};
In console I am not getting any information.
I fixed the problem by using right URL with the port number in Authorized JavaScript origins field in "Create a Project and Client ID" section.
And I also enabled Google+ Api for the project.

GitHub REST API to create Issues with creator parameter

NodeJS APP:
I try to create github issues from my nodeJS application using Github REST API "https://github.com/api/v3/repos/{owner}/{repo}/issues" with the following parameter and Token. I am passing the parameter "creator" to display who created/commented this issue. But it is displaying the owner of the gitHub Access token as the creator of the issue. How to fix this
request.post({
url: githubApiEndpoint + "/repos/" + options.orgName + "/" + options.repoName + "/issues",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + options.accessToken
},
body: JSON.stringify({
title: "creating issue",
body: "description of issue",
creator: "username",
labels: ["question"]
})
}, callback);
As per the documentation you cannot. creator is no valid parameter. Besides that your example is syntactically incorrect.
You can't. OAuth protocol aims to provide a way to do actions in the name of a specific user, the user who owns the token you get.
So, if you create an issue, the author/creator will be the token owner. You cannot do actions in behalf of another person if you don't have his token

Can't get HMAC Authentication working with API

I'm trying to authenticate using HMAC with the LocalBitcoins API.
Here is the authentication written in Python:
message = str(nonce) + hmac_auth_key + relative_path + get_or_post_params_urlencoded
signature = hmac.new(hmac_auth_secret, msg=message, digestmod=hashlib.sha256).hexdigest().upper()
And the parameters to create the HMAC message:
Nonce. A 63 bit positive integer, for example unix timestamp as milliseconds.
HMAC authentication key. This is the first one of a key/secret pair.
Relative path, for example /api/wallet/.
GET or POST parameters in their URL encoded format, for example foo=bar&baz=quux.
Here is how I am building the HMAC:
var milliseconds = (new Date).getTime();
var key = config.key;
var secret = config.secret;
var nonce = milliseconds.toString()
var message = nonce + key + 'api/myself';
var hmac_digest = crypto.createHmac("sha256", secret).update(message).digest('hex').toUpperCase();
The signature is sent via 3 HTTP Headers. The options for the call to the api/myself method looks like such (using request):
{ url: 'https://localbitcoins.com/api/myself',
method: 'GET',
headers:
{ 'Apiauth-Key': 'my api key',
'Apiauth-Nonce': 1439925212276,
'Apiauth-Signature': 'the created signature' },
timeout: 5000 }
And the request:
var req = request.get(options, function(error, response, body) {
console.log(body);
});
But everytime I get the following error message:
{ error:
{ message: 'HMAC authentication key and signature was given, but they are invalid.',
error_code: 41 } }
I've tried lots of different combinations in testing but can't get anything to work. What am I missing?
It turns out that my path was wrong.
/path needed to be /path/, which I found out through working with a working Python implementation.
The package is up and running now here: https://github.com/mrmayfield/localbitcoins-node
I think that (new Date).getTime(); is not creating a 63 bit integer. Per Dr. Axel's post. JavaScript has 53 bit integers plus a sign.

Resources