Google Secret Manager INVALID_ARGUMENT Error - node.js

I'm using Google Secret Manager to access/store some secret parameters in an API. I have no problem saving secrets and accessing versions.
But when I send a request to list these secrets, I keep getting this error.
Error: 3 INVALID_ARGUMENT: Invalid resource field value in the request.
code: 3,
details: 'Invalid resource field value in the request.',
metadata: Metadata {
internalRepr: Map(3) {
'grpc-server-stats-bin' => [Array],
'google.rpc.errorinfo-bin' => [Array],
'grpc-status-details-bin' => [Array]
},
options: {}
},
statusDetails: [
ErrorInfo {
metadata: [Object],
reason: 'RESOURCE_PROJECT_INVALID',
domain: 'googleapis.com'
}
],
reason: 'RESOURCE_PROJECT_INVALID',
domain: 'googleapis.com',
errorInfoMetadata: {
method: 'google.cloud.secretmanager.v1.SecretManagerService.ListSecrets',
service: 'secretmanager.googleapis.com'
}
}
I've also checked the docs and tried different queries like in here but no dice...
This is the part of the code I'm running:
import { SecretManagerServiceClient } from "#google-cloud/secret-manager";
const secretClient = new SecretManagerServiceClient({
keyFile: "foo/bar/google_credentials.json"
});
const [secrets] = await secretClient.listSecrets({
filter: `labels.environment=development`
});
Version of the "#google-cloud/secret-manager": "^4.1.2",

Okay, I found the issue. I had to add the parent param to the request body.
So it should look like this:
const [secrets] = await SecretManager.secretClient.listSecrets({
parent: "projects/**", <=========== This is the key
filter: `
labels.environment:development AND
labels.scope:some-scope AND
labels.customer_id:*`
});

Related

How to properly send a GraphQL update request using Axios?

I created an application using AWS Amplify, and I want to create an endpoint in an API function that will mutate a field in GraphQL. Since its a nodejs API function, I cannot use the recommended libraries from the AWS documentation which use ES6, since the functions can only use ES5. Therefore I need to use Axios.
I created a graphql query:
const query = /* GraphQL */ `mutation updatePublication($id: ID!, $keywords: String) {
updatePublication(id: $id, keywords: $keywords){
id
keywords
}
}`
Next, I created the Axios request based on this StackOverflow question.
const data = await axios.post(
process.env.API_APPNAME_GRAPHQLAPIENDPOINTOUTPUT,
{
query: query,
variables: {
id: variableWithID,
keywords: "updated keywords!"
}
},
{
headers: {
'Content-Type': 'application/json',
'x-api-key': process.env.API_APPNAME_GRAPHQLAPIKEYOUTPUT
}
}
)
When I run the query, I get a status 200 from the server with the following errors:
data: null,
errors: [
{
path: null,
locations: [Array],
message: "Validation error of type MissingFieldArgument: Missing field argument input # 'updatePublication'"
},
{
path: null,
locations: [Array],
message: "Validation error of type UnknownArgument: Unknown field argument id # 'updatePublication'"
},
{
path: null,
locations: [Array],
message: "Validation error of type UnknownArgument: Unknown field argument keywords # 'updatePublication'"
}
]
}
Can anyone advise on what this means?

Axios request working fine by itself but when I try to integrate it with my discord bot it always returns an error?

const { SlashCommandBuilder } = require("#discordjs/builders");
const axios = require("axios")
const { XRapidAPIKey, XRapidAPIHost} = require("../config.json");
module.exports = {
data: new SlashCommandBuilder()
.setName('stock')
.setDescription('Replies with the name of the stock and its current price.')
.addStringOption(option =>
option.setName('ticker')
.setDescription('The stock you want the price of.')
.setRequired(true)),
async execute(interaction) {
const ticker = interaction.options.getString('ticker');
const options = {
method: 'GET',
url: `https://realstonks.p.rapidapi.com/${ticker.toUpperCase()}`,
headers: {
"X-RapidAPI-Key": XRapidAPIKey,
"X-RapidAPI-Host": XRapidAPIHost
}
};
axios.request(options).then(function(response) {
interaction.reply(response.data);
}).catch(function(error) {
console.log(error);
});
}
this is the code for the stock price command but it does not work due to an error being thrown. It should send a message in my discord server with the json data from the axios request. It at first didn't work because I tried to put it in a function and return it but I realized that it needs to be in the command function but I cannot figure out why the request is returning a http 400 code even though it works fine by itself.
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async RequestHandler.push (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async CommandInteraction.reply (/Users/lukepitstick/personal/js/stocktrader/node_modules/discord.js/src/structures/interfaces/InteractionResponses.js:103:5) {
method: 'post',
path: '/interactions/986055380461301820/aW50ZXJhY3Rpb246OTg2MDU1MzgwNDYxMzAxODIwOnY5c1QzbDdIWVN0NW4zY2d4ODd6M2RRSHA1OVpORHZ5SmFXUkNyY0pKZDNpNGNyVjFtQzZ5UjFYck96ZHhJUVlVNjJ6YWNHRTBFbFBSczlWWXBTdHk2YzFuNFJrRFU5R3R3dDAyQ3ByRmtiaTBpRm1NYUVyRXVHYjhsUk84T25t/callback',
code: 50006,
httpStatus: 400,
requestData: {
json: {
type: 4,
data: {
content: undefined,
tts: false,
nonce: undefined,
embeds: undefined,
components: undefined,
username: undefined,
avatar_url: undefined,
allowed_mentions: undefined,
flags: undefined,
message_reference: undefined,
attachments: undefined,
sticker_ids: undefined
}
},
files: []
}
}
But when I run the code in its own file without the discord related stuff and console.log the data it outputs the json data as you would expect.

Error thrown when trigger method called in pusher, "expected string"

I'm trying to configure pusher on my nodejs app.
const Pusher = require("pusher");
const pusher = new Pusher({
appId: "id",
key: "key",
secret: "secret",
cluster: "ap2",
useTLS: true,
});
pusher.trigger('my-channel', 'my-event', {
message: "Hello, world."
}).then(console.log).catch(e=> console.log(e))
When I put above code in index and run, I get following error message.
{
name: 'PusherRequestError',
message: 'Unexpected status code 400',
url: 'a URL with all secret and stuff',
error: undefined,
status: 400,
body: 'expected string\n'
}
I double-checked the keys, secrets, etc and they are all correct. Any help is appreciated. Thanks!

Access HashiCorp Vault KV secret using node-vault

I'm trying to access HashiCorp Vault KV with "node-vault" but keep getting "statusCode: 404"
I'm following the example of node-vault
https://github.com/kr1sp1n/node-vault
1) I'm running vault_1.1.3_windows_amd64 on windows 10 with "vault server -dev" on a PowerShell.
2) Then on another PowerShell runs following;
$env:VAULT_ADDR="http://127.0.0.1:8200"
vault secrets enable -version=1 kv
vault status
Key Value
--- -----
Seal Type shamir
Initialized true
Sealed false
Total Shares 1
Threshold 1
Version 1.1.3
Cluster Name vault-cluster-28a041c6
Cluster ID 0ec85d70-8e87-dff6-347f-b1959fad8b44
HA Enabled false
3) Then runs the following code with the
const rootKey = //whatever;
const unsealKey = //whatever;
var options = {
apiVersion: 'v1',
endpoint: 'http://127.0.0.1:8200',
token: rootKey
};
var vault = require("node-vault")(options);
vault.unseal({ key: unsealKey })
.then(() => {
vault.write('secret/hello', { value: 'world' })
.then((res) => console.log(res))
.catch((err) => console.error(err));
});
vault.write('secret/hello', { value: 'world', lease: '1s' })
.then( () => vault.read('secret/hello'))
.then( () => vault.delete('secret/hello'))
.catch(console.error);
This return a status 404, what needs to be done additionally to avoid 404?
{ Error: Status 404
at handleVaultResponse (XX\TestCodes\Node-VaultTest\node_modules\node-vault\src\index.js:49:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
response:
{ statusCode: 404,
body:
{ request_id: '2992e6c2-5146-6569-1f48-55f75da88993',
lease_id: '',
renewable: false,
lease_duration: 0,
data: null,
wrap_info: null,
warnings: [Array],
auth: null } } }
{ Error: Status 404
at handleVaultResponse (XX\TestCodes\Node-VaultTest\node_modules\node-vault\src\index.js:49:21)
at process._tickCallback (internal/process/next_tick.js:68:7)
response:
{ statusCode: 404,
body:
{ request_id: '2f280fa4-6596-c06f-2168-091246e0a2a1',
lease_id: '',
renewable: false,
lease_duration: 0,
data: null,
wrap_info: null,
warnings: [Array],
auth: null } } }
You mounted the kv store as a version 1. The actual path used by node-vault to read a secret from a version 2 kv store is different and not compatible with Vault's v1 kv store.
Mount your kv store with -version 2. If unspecified, it defaults to v1.
Also bear in mind that you need to add "data" to your path to get it working.
I for instance had kv/mySecret since "mySecret" was in the root "folder". Even though you need to add kv/data/mySecret. Then it worked for me!

NODEJS Marklogic - Write document list cannot process response with 404 status when using documents.write()

I'm new to nodejs and marklogic, and I'm following a tutorial for a simple app, I have setup and configured my marklogin login credentials,
when I run this sample code by running node sample.js
the output is write document list cannot process response with 404 status
I wonder why I'm encountering this error,
here is the code from the tutorial,
my-connection.js
module.exports = {
connInfo: {
host: '127.0.0.1',
port: 8001,
user: 'user',
password: 'password'
}
};
sample.js
const marklogic = require('marklogic');
const my = require('./my-connection.js');
const db = marklogic.createDatabaseClient(my.connInfo);
const documents = [
{ uri: '/gs/aardvark.json',
content: {
name: 'aardvark',
kind: 'mammal',
desc: 'The aardvark is a medium-sized burrowing, nocturnal mammal.'
}
},
{ uri: '/gs/bluebird.json',
content: {
name: 'bluebird',
kind: 'bird',
desc: 'The bluebird is a medium-sized, mostly insectivorous bird.'
}
},
{ uri: '/gs/cobra.json',
content: {
name: 'cobra',
kind: 'mammal',
desc: 'The cobra is a venomous, hooded snake of the family Elapidae.'
}
},
];
db.documents.write(documents).result(
function(response) {
console.log('Loaded the following documents:');
response.documents.forEach( function(document) {
console.log(' ' + document.uri);
});
},
function(error) {
console.log('error here');
console.log(JSON.stringify(error, null, 2));
}
);
I hope someone can tell me what is wrong with the code,
Thank You!
The MarkLogic NodeJS Client library is meant to run against a so-called MarkLogic REST-api instance. There is typically one running at port 8000, but you can also deploy other ones at different ports by issuing a POST call to :8002/v1/rest-apis, as described here:
http://docs.marklogic.com/REST/POST/v1/rest-apis
Port 8001 however is reserved for the MarkLogic Admin UI, which doesn't understand the REST calls that the NodeJS Client library is trying to invoke, hence the 404 (not found)..
HTH!

Resources