I'm trying to view the contents of a cookieJar response from a request to google:
package main
import (
"fmt"
"log"
"net/http"
"net/http/cookiejar"
"net/url"
)
func main() {
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
client := http.Client{Jar: jar}
resp, err := client.Get("https://accounts.google.com/ServiceLogin?continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Ffeature%3Dsign_in_button%26hl%3Den%26action_handle_signin%3Dtrue%26next%3D%252F%26app%3Ddesktop&service=youtube&sacu=1&passive=1209600&ignoreShadow=0&acui=0#identifier")
if err != nil {
log.Fatal(err)
}
fmt.Println(resp.Cookies())
s := ".google.com"
u, err := url.Parse(s)
fmt.Println(client.Jar.Cookies(u))
}
The response is a blank array but I can see that there are cookies being set. How do I view the contents of a cookieJar in Golang?
Unfortunately not, the cookie jar in the std library is completely opaque and can be queried via (non-wildcard) URLs only.
Although Volker is technically correct in the sense that the net/http/cookiejar implementation is opaque, the http.Client.Jar field is an interface (http.Client.CookieJar).
So it is possible to define and use an implementation that provides a list function or exposes a map of URL to cookies. Such an implementation should be based on the std library's implementation to leverage the security features it implements.
If there's any interest, I might provide some sample code.
Related
I had a simple function which connects to mongoDB and create a new document.
Now how do I mock the methods of the imported mongo package while unit testing.
Ive tried to mock GinContext by monkeypatching.
But unable to proceed with mocking the actual mongoClient as the package is imported.
func CreateUser(c GinContext) {
var userdetail UserDetails
binderr := c.ShouldBindJSON(&userdetail)
fmt.Println(binderr)
if binderr != nil {
c.JSON(500, gin.H{
"message": "Input payload not matching",
"error": binderr,
})
return
}
//-- Client if of type *mongo.Client.
//-- How do I mock the Client.Database, Client.Database.Connection
collection := Client.Database("demo").Collection("users")
ctx, err1 := context.WithTimeout(context.Background(), 10*time.Second)
if err1 != nil {
}
response, err2 := collection.InsertOne(ctx, userdetail)
if err2 != nil {
log.Println("Some error inserting the document")
}
fmt.Println(response.InsertedID)
c.JSON(200, gin.H{
"message": "User created successfully",
})
}
Expected: I should be able to mock or stub Client and provide dummy functionality. Just like in nodeJS we do
spyOn(Client,'Database').and.return(Something)
Every time I'm wondering "how to mock a method", this is mostly related to my code architecture. Not being able to test easily some code means, most of time, that the code is poorly designed and/or too coupled to the used libraries/frameworks. Here, you want to mock Mongo connection only because your code is too tightly related to Mongo (in the CreateUser function). Refactoring could help you to test your code (without any Mongo connection).
I've experienced that using interfaces and dependency injection simplifies
the testing process in Go, and clarifies the architecture. Here is my attempt to help you test your application.
Code refactoring
First, define what you want to do with an interface. Here, you're inserting users, so let's do a UserInserter interface, with a single method for now (Insert, to insert a single user) :
type UserInserter interface {
Insert(ctx context.Context, userDetails UserDetails) (insertedID interface{}, err error)
}
In the code you have provided, you are only using the insertedID, so you probably only need it as output of this Insert method (and an optional error if something gone wrong). insertedID is defined as an interface{} here, but feel free to change to whatever you want.
Then, let's modify your CreateUser method and inject this UserInserter as a parameter :
func CreateUser(c *gin.Context, userInserter UserInserter) {
var userdetail UserDetails
binderr := c.ShouldBindJSON(&userdetail)
fmt.Println(binderr)
if binderr != nil {
c.JSON(500, gin.H{
"message": "Input payload not matching",
"error": binderr,
})
return
}
// this is the modified part
insertedID, err2 := userInserter.Insert(c, userdetail)
if err2 != nil {
log.Println("Some error inserting the document")
}
fmt.Println(insertedID)
c.JSON(200, gin.H{
"message": fmt.Sprintf("User %s created successfully", insertedID),
})
}
This method could be refactored but, to avoid any confusion, I will not touch it.
userInserter.Insert(c, userdetail) replaces here the Mongo dependency in this method by injecting userInserter.
You can now implement your UserInserter interface with the backend of your choice (Mongo in your case). Insertion into Mongo needs a Collection object (the collection we are inserting the user in), so let's add this as an attribute :
type MongoUserInserter struct {
collection *mongo.Collection
}
Implementation of Insert method follows (call InsertOne method on *mongo.Collection) :
func (i MongoUserInserter) Insert(ctx context.Context, userDetails UserDetails) (insertedID interface{}, err error) {
response, err := i.collection.InsertOne(ctx, userDetails)
return response.InsertedID, err
}
This implementation could be in a separated package and should be tested separately.
Once implemented, you can use MongoUserInserter in your main application, where Mongo is the backend. MongoUserInserter is initialized in the main function, and injected in the CreateUser method. Router setup have been separated (also for testing purpose) :
func setupRouter(userInserter UserInserter) *gin.Engine {
router := gin.Default()
router.POST("/createUser", func(c *gin.Context) {
CreateUser(c, userInserter)
})
return router
}
func main() {
client, _ := mongo.NewClient()
collection := client.Database("demo").Collection("users")
userInserter := MongoUserInserter{collection: collection}
router := setupRouter(userInserter)
router.Run(":8080")
}
Note that if some day you want to change the backend, you will only
need to change the userInserter in the main function!
Tests
From a tests perspective, it is now easier to test because we can create a fake UserInserter, like :
type FakeUserInserter struct{}
func (_ FakeUserInserter) Insert(ctx context.Context, userDetails UserDetails) (insertedID interface{}, err error) {
return userDetails.Name, nil
}
(I supposed here UserDetails have an attribute Name).
If you really want to mock this interface, you can take a look at GoMock. In this case though, I'm not sure using a mock framework is required.
And now we can test our CreateUser method with a simple HTTP testing framework (see https://github.com/gin-gonic/gin#testing), without needing a Mongo connection or mocking it.
import (
"bytes"
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestCreateUser(t *testing.T) {
userInserter := FakeUserInserter{}
router := setupRouter(userInserter)
w := httptest.NewRecorder()
body := []byte(`{"name": "toto"}`)
req, _ := http.NewRequest("POST", "/createUser", bytes.NewBuffer(body))
router.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
assert.Equal(t, `{"message":"User toto created successfully"}`, w.Body.String())
}
Note that this does not exempt to also test Insert method of MongoUserInserter, but separately : here, this test covers CreateUser, not the Insert method.
Hello StackOverflow AWS Gophers,
I'm implementing a CLI with the excellent cobra/viper packages from spf13. We have an Athena database fronted by an API Gateway endpoint, which authenticates with IAM.
That is, in order to interact with its endpoints by using Postman, I have to define AWS Signature as Authorization method, define the corresponding AWS id/secret and then in the Headers there will be X-Amz-Security-Token and others. Nothing unusual, works as expected.
Since I'm new to Go, I was a bit shocked to see that there are no examples to do this simple HTTP GET request with the aws-sdk-go itself... I'm trying to use the shared credentials provider (~/.aws/credentials), as demonstrated for the S3 client Go code snippets from re:Invent 2015:
req := request.New(nil)
How can I accomplish this seemingly easy feat in 2019 without having to resort to self-cooked net/http and therefore having to manually read ~/.aws/credentials or worse, go with os.Getenv and other ugly hacks?
Any Go code samples interacting as client would be super helpful. No Golang Lambda/server examples, please, there's plenty of those out there.
Unfortunately, it seems that the library has been updated since the accepted answer was written and the solution no longer is the same. After some trial and error, this appears to be the more current method of handling the signing (using https://pkg.go.dev/github.com/aws/aws-sdk-go-v2):
import (
"context"
"net/http"
"time"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)
func main() {
// Context is not being used in this example.
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
// Handle error.
}
credentials, err := cfg.Credentials.Retrieve(context.TODO())
if err != nil {
// Handle error.
}
// The signer requires a payload hash. This hash is for an empty payload.
hash := "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
req, _ := http.NewRequest(http.MethodGet, "api-gw-url", nil)
signer := v4.NewSigner()
err = signer.SignHTTP(context.TODO(), credentials, req, hash, "execute-api", cfg.Region, time.Now())
if err != nil {
// Handle error.
}
// Use `req`
}
The solution below uses aws-sdk-go-v2
https://github.com/aws/aws-sdk-go-v2
// A AWS SDK session is created because the HTTP API is secured using a
// IAM authorizer. As such, we need AWS client credentials and a
// session to properly sign the request.
cfg, err := external.LoadDefaultAWSConfig(
external.WithSharedConfigProfile(profile),
)
if err != nil {
fmt.Println("unable to create an AWS session for the provided profile")
return
}
req, _ := http.NewRequest(http.MethodGet, "", nil)
req = req.WithContext(ctx)
signer := v4.NewSigner(cfg.Credentials)
_, err = signer.Sign(req, nil, "execute-api", cfg.Region, time.Now())
if err != nil {
fmt.Printf("failed to sign request: (%v)\n", err)
return
}
res, err := http.DefaultClient.Do(req)
if err != nil {
fmt.Printf("failed to call remote service: (%v)\n", err)
return
}
defer res.Body.Close()
if res.StatusCode != 200 {
fmt.Printf("service returned a status not 200: (%d)\n", res.StatusCode)
return
}
The first argument to request.New is aws.Config, where you can send credentials.
https://github.com/aws/aws-sdk-go/blob/master/aws/request/request.go#L99
https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
There are multiple ways to create credentials object: https://docs.aws.amazon.com/sdk-for-go/v1/developer-guide/configuring-sdk.html
For example using static values:
creds:= credentials.NewStaticCredentials("AKID", "SECRET_KEY", "TOKEN")
req := request.New(aws.Config{Credentials: creds}, ...)
I'm pretty new to go myself (3rd day learning go) but from watching the video you posted with the S3 example and reading through the source code (for the s3 service and request module) here is my understanding (which I'm hoping helps).
If you look at the code for the s3.New() function aws-sdk-go/service/s3/service.go
func New(p client.ConfigProvider, cfgs ...*aws.Config) *S3 {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, .SigningName) }
As opposed to request.New() function aws-sdk-go/aws/request/request.go
func New(cfg aws.Config, clientInfo metadata.ClientInfo, handlers Handlers,
retryer Retryer, operation *Operation, params interface{}, data interface{}) *Request { ...
As you can see in the s3 scenario the *aws.Config struct is a pointer, and so is probably initialized / populated elsewhere. As opposed to the request function where the aws.Config is a parameter. So I am guessing the request module is probably a very low level module which doesn't get the shared credentials automatically.
Now, seeing as you will be interacting with API gateway I had a look at that service specifically to see if there was something similar. I looked at aws-sdk-go/service/apigateway/service.go
func New(p client.ConfigProvider, cfgs ...*aws.Config) *APIGateway {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName) }...
Which looks pretty much the same as the s3 client, so perhaps try using that and see how you go?
I'm using AWS Cognito to authenticate my users, and once authenticated, they can call my API (API Gateway + Lambda). I'm doing all that using the Serverless Framework.
Once authenticated, when they call an endpoint that requires this authentication, my lambda will receive the user attributes through the request.RequestContext.Authorizer["claims"]. I had the idea of creating an authentication middleware to inject the current user into the context. But I'm certain that I'm doing something wrong (or can be improved).
How it works:
my-lambda.go:
package main
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/company/api/middlewares"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
fmt.Println(ctx.user)
return events.APIGatewayProxyResponse{}, nil
}
func main() {
lambda.Start(
middlewares.Authentication(Handler),
)
}
middlewares/authentication.go
package middlewares
import (
"context"
"github.com/aws/aws-lambda-go/events"
"github.com/company/api/models"
)
func Authentication(next func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error)) func(context.Context, events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
var user models.User
return func(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
claims := request.RequestContext.Authorizer["claims"]
// Find user by claims properties.
if err := user.Current(claims); err != nil {
return events.APIGatewayProxyResponse{}, err
}
ctx.user = user
return next(ctx, request)
}
}
models/user.go:
package models
import (
"github.com/jinzhu/gorm"
"github.com/mitchellh/mapstructure"
)
type User struct {
gorm.Model
// Override ID cause we are using cognito.
Email string `gorm:"primary_key,not null"`
Site Site
}
func (u *User) Current(claims interface{}) error {
if err := mapstructure.Decode(claims, u); err != nil {
panic(err)
}
if err := Database.Find(u).Error; err != nil {
return err
}
return nil
}
I have 2 questions:
Is this the right way to define a function (Authentication function) that receives a function and returns another function? Because it is too verbose, I am feeling this is wrong.
Is there a way to augment the ctx with an user attribute? The way that I'm trying, I see the error ctx.user undefined (type context.Context has no field or method user).
1st question about using the middleware:
There is certainly nothing wrong with the approach. Maybe the function will look a little better if you define the function type and use the defined name. net/http does the same thing with the HandlerFunc:
type HandlerFunc func(ResponseWriter, *Request)
Which will make the signature of a middleware more reasonable:
func AuthMiddleware(nextHop HandlerFunc) HandlerFunc
EDIT: doesn't the lambda library define such a type for the function signature? I would expect one to exist.
Also I don't know if the suffix Middleware makes sense in your case, but I think some suffix should make sense for you to give a little more context to the name of the function and make it more understandable. AuthenticationMiddleware could be an example.
EDIT: just saw the package name. LGTM really.
2nd question:
See this for the correct use of context. There's also a common pitfal: context.WithValue returns a new context to use. Therefore you should not expect the passed parameter context to be mutated and should use the new one that is returned.
I have an S3-triggered AWS Lambda written in Go. I've been able to successfully test all of the ancillary code, however, I'm stuck trying to test the lambda handler.
Here's the signature of my handler:
func HandleRequest(ctx context.Context, s3Event events.S3Event)
Here's the test code:
package main
import (
"context"
"encoding/json"
"testing"
"github.com/aws/aws-lambda-go/events"
"github.com/stretchr/testify/assert"
)
func TestHandleRequest(t *testing.T) {
// 1. read JSON from file
inputJSON, err := readJSONFromFile("./testdata/s3-event.json")
if err != nil {
t.Errorf("could not open test file. details: %v", err)
}
// 2. de-serialize into Go object
var inputEvent events.S3Event
if err := json.Unmarshal(inputJSON, &inputEvent); err != nil {
t.Errorf("could not unmarshal event. details: %v", err)
}
// 3. How can I mock the context.Context?
assert.NoError(t, HandleRequest(context.Context, inputEvent))
}
I have no clue how I should mock the context.Context. I couldn't find any examples online either.
Anyone know? Does my code look idiomatic for testing an S3-triggered, Go Lambda?
‘context.Context’ is designed to be an immutable value (even though it is literally an interface). So I wouldn’t be concerned with mocking it.
There are two ways to create empty contexts (‘context.Background()’ and ‘context.TODO()’). I would start with those. If you want to set something on the context, check out documentation on the context package.
Will context.TODO satisfy your needs?
https://golang.org/pkg/context/#TODO
I'm trying to use Go to log into my account on Amazon to automatically pull some information, but I'm having trouble logging in because it complains about cookies. Here's a sanitized version of the code I was using:
package main
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"strconv"
)
func CheckThis(AmazonUsername string, AmazonPassword string) error {
var LogonURL string
// Set the url
LogonURL = "https://www.amazon.com/ap/signin"
// Craft some form data
form := url.Values{}
form.Add("appAction", "SIGNIN")
form.Add("email", AmazonUsername)
form.Add("password", AmazonPassword)
form.Add("create", "0")
form.Add("appActionToken", “$VALUE”)
form.Add("openid.pape.max_auth_age", "$VALUE==")
form.Add("openid.identity", "$VALUE=")
form.Add("openid.assoc_handle", "$VALUE")
form.Add("openid.mode", "$VALUE")
form.Add("openid.ns.pape", "$VALUE==")
form.Add("openid.claimed_id", "$VALUE=")
form.Add("pageId", "$VALUE")
form.Add("openid.ns", "$VALUE=")
// Amazon sells cookies
cookieJar, _ := cookiejar.New(nil)
// Create a new client with the cookiejar in the struct...
client := &http.Client{
Jar: cookieJar,
}
// Craft the request to send to the website with the form containing login info
req, _ := http.NewRequest("POST", LogonURL, bytes.NewBufferString(form.Encode()))
// Some more headers
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
req.Header.Add("Content-Length", strconv.Itoa(len(form.Encode())))
req.Header.Add("Accept-Language", "en-US,en;q=0.8")
req.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8")
req.Header.Add("Connection", "keep-alive")
req.Header.Add("Host", "www.amazon.com")
req.Header.Add("Referer", "https://www.amazon.com/ap/signin")
req.Header.Add("Upgrade-Insecure-Requests", "1")
req.Header.Add("Origin", "https://www.amazon.com")
req.Header.Add("Cache-Control", "max-age=0")
// And we're off to the races...
resp, _ := client.Do(req)
// What was in the response?
charResponse, _ := ioutil.ReadAll(resp.Body)
resp.Body.Close()
// Write response body to a text file with title of…
_ = WriteOutputToFile(string(charResponse), “response.html")
// All done!
return nil
}
The $VALUE entries are because I'm not sure if the strings are significant to my account so I removed them; these are values I pulled from the developer tools of a Chrome login session. I also removed err checks for brevity.
The reply page (opening response.html on my drive within Chrome) looks like this:
What am I missing in order to keep the cookie with the client req/resp for the sign-in and later pages?
Or am I missing something where the response page I save is trying to pull elements from Amazon when I render the HTML, and the cookie issue is because the browser would be missing cookie information when I'm trying to view the results from the Go application?
I'm pretty sure Amazon uses different data every time when you try to login so better to parse login form. Here is example
package main
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"net/url"
"github.com/PuerkitoBio/goquery"
"log"
)
func checkError(err error) {
if err != nil {
log.Fatal(err)
}
}
func CheckThis(AmazonUsername string, AmazonPassword string) error {
cookieJar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: cookieJar,
}
res, err := client.Get("https://www.amazon.com/gp/sign-in.html/ref=ord_cart_unrec_signin")
checkError(err)
doc, err := goquery.NewDocumentFromResponse(res)
form := url.Values{}
doc.Find("form[name='signIn'] input").Each(func(i int, s *goquery.Selection) {
name, exist := s.Attr("name")
if exist {
value, exist := s.Attr("value")
if exist {
form.Add(name, value)
}
}
})
form.Set("email", AmazonUsername)
form.Set("password", AmazonPassword)
req, _ := http.NewRequest("POST", "https://www.amazon.com/ap/signin", bytes.NewBufferString(form.Encode()))
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
res, err = client.Do(req)
checkError(err)
defer res.Body.Close()
charResponse, _ := ioutil.ReadAll(res.Body)
ioutil.WriteFile("response.html", charResponse, 0777)
return nil
}
func main() {
CheckThis("", "")
}
Amazon's index is setting this (and much more) cookies on my browser:
I suppose you need to set them into cookiejar in order to simulate a browser (amazon excepts that from your request, so is telling you have no cookies enabled because there isn't a required security value).
I agree with #JimB, you should be using Amazon SDK. Is there any reason why you are not doing this way?
Best regards.