HashiCorp Vault + node-vault + write = 404 - hashicorp-vault

I'm trying a simple operation using node-vault but it is not working. Here is my attempt:
Configuration
var options = {
apiVersion: 'v2', // default
endpoint: 'http://127.0.0.1:8200', // default
};
// get new instance of the client
var vault = require("node-vault")(options);
vault.token = "<<MY TOKEN>>";
Usage
vault.write('secret/data/new', {"data": {"foo": "bar"}}).then(
function (value: any) {
console.log(value);
})
.catch((err: any) => {
console.log(err);
});
Response
{ statusCode: 404, body: { errors: [] } }
But, if I run vault kv put secret/data/new foo=bar it does work and value is there.
What is going on?
Thank you all and I wish a happy new year!

Ok, here is what I did.
Reinstall Vault, something happened to storage because I did a lot of attempts and commands in it.
Enable secrets engine in specific path vault secrets enable -path=testPath kv
Write to this path
Configure:
export const VAULT_OPTIONS = {
apiVersion: 'v1',
endpoint: 'http://127.0.0.1:8200',
token: '<<YOUR TOKEN>>'
};
vault = require("node-vault")(VAULT_OPTIONS);
Write:
this.vault.write('test/data/mykey', {"data": {"tests": {"test1": "test1-value", "test2": "test2-value"}}}).then(
(result: any) => {
console.log(res.data);
}, (error: any) => {
console.log(error);
});
Please note that path must contain data and data must be surounded by data ({ data: {key:value}) as well.

Related

Connection between MongoDB Atlas and AWS giving timeout error?

I'm new to AWS so I apologize for any newbie stuff.
I'm trying to connect a MongoDB Atlas M0 cluster with our AWS EC2 instance, which is running a nodejs / react stack. The problem is that I can't make these two instances connect - AWS and MongoDB that is. When trying to use the backend sign in function (our nodejs api), it just gives this error:
Operation `user_profile.findOne()` buffering timed out after 10000ms
This is our index / connection:
import config from './config';
import app from './app';
import { connect } from 'mongoose'; // MongoDB
import { ServerApiVersion } from 'mongodb';
import https from 'https';
import AWS from 'aws-sdk';
const makeLogger = (bucket: string) => {
const s3 = new AWS.S3({
accessKeyId: <ACCESS_KEY_ID>,
secretAccessKey: <SECRET_ACCESS_KEY>
});
return (logData: any, filename: string) => {
s3.upload({
Bucket: bucket, // pass your bucket name
Key: filename, // file will be saved as testBucket/contacts.csv
Body: JSON.stringify(logData, null, 2)
}, function (s3Err: any, data: any) {
if (s3Err) throw s3Err
console.log(`File uploaded successfully at ${data.Location}`)
});
console.log(`log (${filename}): ${logData}`);
};
};
const log = makeLogger('xxx-xxxx');
log(config.MONGO_DB_ADDRESS, 'mongo_db_address.txt');
const credentials = <CREDENTIALS>
connect(config.MONGO_DB_ADDRESS, {
sslKey: credentials,
sslCert: credentials,
serverApi: ServerApiVersion.v1
}) //, { useNewUrlParser: true })
.then(() => console.log('Connected to MongoDB'))
.catch((err) => console.error('Failed connection to MongoDB', err));
app.on('error', error => {
console.error('app error: ' + error);
});
app.listen(config.WEB_PORT, () => {
console.log(`Example app listening on port ${config.WEB_PORT}`);
});
One of the endpoints giving the timeout error:
router.post('/signin', async (req, res) => {
var form_validation = signin_schema.validate({
email: req.body.email,
password: req.body.password,
});
if (form_validation.error) {
console.log('form validation sent');
//return res.status(400).send(form_validation);
return res.status(400).send({
kind: 'ERROR',
message: 'Sorry - something didn\'t go well. Please try again.'
});
}
var User = model('model', UserSchema, 'user_profile');
User.findOne({ email: req.body.email }, (err: any, the_user: any) => {
if (err) {
return res.status(400).send({
kind: 'ERROR',
message: err.message
});
}
if (!the_user) {
return res.status(400).send({
kind: 'ERROR',
message: 'the_user undefined',
});
}
compare(req.body.password, the_user.password)
.then((result) => {
if (result == true) {
const user_payload = { name: the_user.name, email: the_user.email };
const access_token = sign(user_payload, config.SECRET_TOKEN);
res.cookie('authorization', access_token, {
httpOnly: true,
secure: false,
maxAge: 3600000,
});
return res.send({ kind: "LOADING" });
// return res.send(access_token);
} else {
return res.status(400).send({
kind: 'ERROR',
message: 'Sorry - wrong password or email used.'
});
}
})
})
});
The strange thing is that I can connect from my local developer machine, when running our frontend. Just as I can connect from wsl2 ubuntu cli.
On the Mongo side, I have whitelisted every possible ip address. On the AWS side, I have created the outbound security group policy required. Regarding the inbound, I think it is correct. I've allowed access on the ports 27000 - 28018.
Again - I'm new to AWS, so if anyone can tell me what it is I'm simply not understanding here, I would be very grateful
Thanks
open mongodb atlas Network Access
open 0.0.0.0/0 (includes your current IP address)

Why isn't my Firebase app connecting to Google Secret Manager?

I can't figure out why I keep getting the error: Error: Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.
firebase login from my command line returns that I am already logged in and
I have configured my-app#appspot.gserviceaccount.com to be a Secret Manager Secret Accessor in the GCP IAM admin dashboard within the same project.
Here's the code I'm using:
const { SecretManagerServiceClient } = require("#google-cloud/secret-manager");
const client = new SecretManagerServiceClient();
const gcpSecretsLoader = async (secretName: string) => {
try {
const secret = await client.accessSecretVersion({
name: `projects/my-app/secrets/${secretName}/versions/latest`,
});
const payload = secret.payload.data.toString("utf8");
console.info(`Payload: ${payload}`);
} catch (err) {
console.log(err);
}
};
gcpSecretsLoader("CLIENT_ID"); // CLIENT_ID matched a secret name within the secret manager

StitchServiceError "aws: "aws_service" is a required string", errorCodeName: InvalidParameter

I'm setting up AWS S3 bucket to upload audio files to using MongoDB Stitch (here are the docs mongo s3 docs . After following the instructions and authenticating my user I keep geting this error when trying to upload the selected file: error image from console
On line 119 where the error is coming from I'm just catching the error after running AWS build:
const aws = stitchClient.getServiceClient(AwsServiceClient.factory, "AWS");
convertAudioToBSONBinaryObject(file).then((result) => {
const audiofile = mongodb.db("data").collection("audiofile");
//now we need an instance of AWS service client
const key = `${stitchClient.auth.user.id}-${file.name}`;
// const key = `${stitchClient.auth.user.id}-${file.name}`;
const bucket = "myBucketName";
const url =
"http://" + bucket + ".s3.amazonaws.com/" + encodeURIComponent(key);
const args = {
ACL: "public-read",
Bucket: bucket,
ContentType: file.type,
Key: key,
Body: result,
// aws_service: "s3",
};
// building the request
const request = new AwsRequest.Builder()
.withService("s3")
.withAction("PutObject")
.withRegion("us-east-1")
.withArgs(args);
aws
.execute(request.build)
.then((result) => {
console.log(result);
console.log(url);
return audiofile.insertOne({
owner_id: stitchClient.auth.user.id,
url,
file: {
name: file.name,
type: file.type,
},
Etag: result.Etag,
ts: new Date(),
});
})
.then((result) => {
console.log("last result", result);
})
.catch((err) => {
console.log(err);
});
});
My Stitch rule for s3 looks like this: Stitch rule for AWS s3
So it seems to me that everything is set up the way it's inteded to, but the error tells me I'm not passing all the needed args. I'd really appreciate any thoughts on how to fix this error.
P.S. If I change "AWS" to "AWS_S3" in this line :
const aws = stitchClient.getServiceClient(AwsServiceClient.factory, "AWS");
The error message changes to this:
StitchServiceError {message: "service not found: 'AWS_S3'", name: "StitchServiceError", errorCode: 18, errorCodeName: "ServiceNotFound",
And the log in Stitch shows this for information for both errors: Stitch Logs
The answer to this is a simple typo in this line:
aws
.execute(request.build)
.then((result)
build is a function so I just needed to call it - (request.build()).then((result).
Issue solved, thanks all!

Meteor: Restivus API call returns HTML template

I must be missing something patently obvious here, but I cannot for the life of me figure out what. I have configured Restivus like this:
Projects = new Mongo.Collection('projects');
Skills = new Mongo.Collection('skills');
Causes = new Mongo.Collection('causes');
Meteor.startup(() => {
let Api = new Restivus({
apiPath: 'api/',
auth: {
token: 'auth.apiKey',
user: function () {
return {
userId: this.request.headers['user-id'],
token: this.request.headers['login-token']
};
}
},
defaultHeaders: {
'Content-Type': 'application/json'
},
onLoggedIn: function () {
console.log(this.user.username + ' (' + this.userId + ') logged in');
},
onLoggedOut: function () {
console.log(this.user.username + ' (' + this.userId + ') logged out');
},
prettyJson: true,
useDefaultAuth: true,
version: 'v1'
});
// Add core models
Api.addCollection(Skills);
Api.addCollection(Causes);
Api.addCollection(Projects);
Api.addRoute('custom', {
get: function () {
return {
status: 'success',
data: 'get something different'
};
}
});
});
This is essentially copy-pasted from the documentation. The problem is that when trying to access either any of the auto-generated endpoints, or the custom endpoint custom, all I get is the HTML of the Meteor app itself (i.e. same as if I had navigated to the root URL of the app).
It is as if Restivus simply is not being run at all, yet a console.log at the end of the code block above verifies that it is at least being run. What am I doing wrong?
As I expected, it was something patently obvious. I am leaving this here just in case anyone else makes the same mistake.
The key is this line in the config:
version: 'v1'
this means that you will need to append /v1/ to your API path, so that the call itself has the format (for example):
mydomain.com/api/v1/myresource

Custom authenticator with Ember simple auth + Ember CLI

I'm trying to write a custom authenticator, similar to the one from this example in the docs. The goal is to be able to retrieve the currently logged in user via session.user.
I'm using Ember CLI, so in initializers/authentication.js I have
import Ember from 'ember';
var customAuthenticator = Ember.SimpleAuth.Authenticators.Devise.extend({
authenticate: function(credentials) {
debugger;
}
});
export default {
name: 'authentication',
initialize: function(container, application) {
Ember.SimpleAuth.Session.reopen({
user: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return container.lookup('store:main').find('user', userId);
}
}.property('userId')
});
// register the custom authenticator so the session can find it
container.register('authenticator:custom', customAuthenticator);
Ember.SimpleAuth.setup(container, application, {
routeAfterAuthentication: 'landing-pages',
authorizerFactory: 'ember-simple-auth-authorizer:devise'
});
}
};
When I try to authenticate, I get the following error:
TypeError: Cannot read property 'authenticate' of undefined
at __exports__.default.Ember.ObjectProxy.extend.authenticate
Any idea why?
As of Simple Auth 0.6.4, you can now do something like:
index.html:
window.ENV['simple-auth'] = {
authorizer: 'simple-auth-authorizer:devise',
session: 'session:withCurrentUser'
};
initializers/customize-session.js:
import Ember from 'ember';
import Session from 'simple-auth/session';
var SessionWithCurrentUser = Session.extend({
currentUser: function() {
var userId = this.get('user_id');
if (!Ember.isEmpty(userId)) {
return this.container.lookup('store:main').find('user', userId);
}
}.property('user_id')
});
export default {
name: 'customize-session',
initialize: function(container) {
container.register('session:withCurrentUser', SessionWithCurrentUser);
}
};
You would need to do something like this:
Em.SimpleAuth.Authenticators.OAuth2.reopen
serverTokenEndpoint: "http://myapp.com/token"
authenticate: (credentials) ->
new Em.RSVP.Promise (resolve, reject) =>
data =
grant_type: "password"
username: credentials.identification
password: credentials.password
#makeRequest(data).then (response) =>
# success call
, (xhr, status, error) ->
# fail call
What I think might be happening is that you are registering the authenticator with the application and not the authenticator itself?
The problem is that the AMD build does not currently automatically register the extension libraries' components (see https://github.com/simplabs/ember-simple-auth/issues/198). I'll change that in the next release and will probably also adopt the documentation to be more focussed on the AMD build instead of the browserified version. For the moment you'd have to run this in your initializer
container.register(
'ember-simple-auth-authorizer:devise',
Ember.SimpleAuth.Authorizers.Devise
);
container.register(
'ember-simple-auth-authenticator:devise',
Ember.SimpleAuth.Authenticators.Devise
);