示例#1
0
// JWTParser parses a JWT if one is found a request's header and stores it in
// a context.
func JWTParser(ctx context.Context, w ResponseWriter, next CtxHandlerFunc) context.Context {
	r := GetRequest(ctx)
	token, err := jwt.ParseFromRequest(r.R, func(token *jwt.Token) (interface{}, error) {
		return publicKey, nil
	})
	if err == nil {
		ctx = context.WithValue(ctx, ctxKey, token)
	}

	// Claims
	idInter := Claim(ctx, "id")
	id := ""
	if i, ok := idInter.(string); ok {
		id = i
	}
	ctx = context.WithValue(ctx, key("id"), id)

	groupsInter := Claim(ctx, "groups")
	groups := []string{}
	if iS, ok := groupsInter.([]interface{}); ok {
		for _, gI := range iS {
			if g, ok := gI.(string); ok {
				groups = append(groups, g)
			}
		}
	}
	ctx = context.WithValue(ctx, key("groups"), groups)

	return next(ctx, w)
}
// NewClient returns a new client
func NewClient(config *Config) (client *Client, err error) {
	// bootstrap the config
	defConfig := DefaultConfig()

	if len(config.ApiAddress) == 0 {
		config.ApiAddress = defConfig.ApiAddress
	}

	if len(config.Username) == 0 {
		config.Username = defConfig.Username
	}

	if len(config.Password) == 0 {
		config.Password = defConfig.Password
	}

	if len(config.Token) == 0 {
		config.Token = defConfig.Token
	}

	ctx := oauth2.NoContext
	if config.SkipSslValidation == false {
		ctx = context.WithValue(ctx, oauth2.HTTPClient, defConfig.HttpClient)
	} else {
		tr := &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
		ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{Transport: tr})
	}

	endpoint, err := getInfo(config.ApiAddress, oauth2.NewClient(ctx, nil))

	if err != nil {
		return nil, fmt.Errorf("Could not get api /v2/info: %v", err)
	}

	authConfig := &oauth2.Config{
		ClientID: "cf",
		Scopes:   []string{""},
		Endpoint: oauth2.Endpoint{
			AuthURL:  endpoint.AuthEndpoint + "/oauth/auth",
			TokenURL: endpoint.TokenEndpoint + "/oauth/token",
		},
	}

	token, err := authConfig.PasswordCredentialsToken(ctx, config.Username, config.Password)

	if err != nil {
		return nil, fmt.Errorf("Error getting token: %v", err)
	}

	config.TokenSource = authConfig.TokenSource(ctx, token)
	config.HttpClient = oauth2.NewClient(ctx, config.TokenSource)

	client = &Client{
		config:   *config,
		Endpoint: *endpoint,
	}
	return client, nil
}
示例#3
0
// Ensures that the httpstore can interpret the errors returned from the server
func TestValidationErrorFormat(t *testing.T) {
	ctx := context.WithValue(
		context.Background(), "metaStore", storage.NewMemStorage())
	ctx = context.WithValue(ctx, "keyAlgorithm", data.ED25519Key)

	handler := RootHandler(nil, ctx, signed.NewEd25519())
	server := httptest.NewServer(handler)
	defer server.Close()

	client, err := store.NewHTTPStore(
		fmt.Sprintf("%s/v2/gun/_trust/tuf/", server.URL),
		"",
		"json",
		"",
		"key",
		http.DefaultTransport,
	)

	_, repo, _ := testutils.EmptyRepo()
	r, tg, sn, ts, err := testutils.Sign(repo)
	assert.NoError(t, err)
	rs, _, _, _, err := testutils.Serialize(r, tg, sn, ts)
	assert.NoError(t, err)

	err = client.SetMultiMeta(map[string][]byte{data.CanonicalRootRole: rs})
	assert.Error(t, err)
	assert.IsType(t, validation.ErrBadRoot{}, err)
}
示例#4
0
func TestGetNote(t *testing.T) {
	assert := assert.New(t)

	dbMap := initDb()
	defer dbMap.Db.Close()
	ctx := context.Background()
	ctx = context.WithValue(ctx, "db", dbMap)
	ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})

	dbMap.Insert(&model.Note{
		Id:        0,
		Title:     "Test Title 1",
		Content:   "lorem ipsum dolor sit amet consetetur.",
		OwnerId:   0,
		CreatedAt: 1442284669000,
		UpdatedAt: 1442292926000,
	})

	kami.Reset()
	kami.Context = ctx
	kami.Post("/api/notes/:noteId", GetNote)
	server := httptest.NewServer(kami.Handler())
	defer server.Close()

	resp := request(t, server.URL+"/api/notes/1", http.StatusOK, nil)
	assert.NotNil(resp)

	note := resp.(map[string]interface{})
	assert.Equal("Test Title 1", note["title"])
	assert.Equal("lorem ipsum dolor sit amet consetetur.", note["content"])
	assert.EqualValues(0, note["ownerId"])
	assert.EqualValues(1442284669000, note["createdAt"])
	assert.EqualValues(1442292926000, note["updatedAt"])
}
示例#5
0
func TestNoMatch(t *testing.T) {
	t.Parallel()

	var rt router
	rt.add(boolPattern(false), HandlerFunc(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		t.Fatal("did not expect handler to be called")
	}))
	_, r := wr()
	ctx := context.Background()
	ctx = context.WithValue(ctx, internal.Pattern, boolPattern(true))
	ctx = context.WithValue(ctx, internal.Pattern, boolPattern(true))
	ctx = context.WithValue(ctx, "answer", 42)

	ctx = context.WithValue(ctx, internal.Path, "/")
	ctx = rt.route(ctx, r)

	if p := ctx.Value(internal.Pattern); p != nil {
		t.Errorf("unexpected pattern %v", p)
	}
	if h := ctx.Value(internal.Handler); h != nil {
		t.Errorf("unexpected handler %v", h)
	}
	if h := ctx.Value("answer"); h != 42 {
		t.Errorf("context didn't work: got %v, wanted %v", h, 42)
	}
}
示例#6
0
func TestPassingContext(t *testing.T) {
	var state1, state2, state3 machine.State

	var result int

	state1 = func(runtime machine.Runtime) {
		first := 1
		ctx := context.WithValue(runtime.Context(), "first", first)
		runtime.NextState(ctx, state2)
	}

	state2 = func(runtime machine.Runtime) {
		first := runtime.Context().Value("first").(int)
		ctx := context.WithValue(runtime.Context(), "second", first+1)
		runtime.NextState(ctx, state3)
	}

	state3 = func(runtime machine.Runtime) {
		second := runtime.Context().Value("second").(int)
		result = second + 1
		runtime.NextState(runtime.Context(), nil)
	}

	runtime := local.Runtime(context.Background(), state1)

	<-runtime.Context().Done()

	if result != 3 {
		t.Errorf("expected %d, but got %d", 3, result)
	}
}
示例#7
0
// Authenticated is a middleware that checks for authentication in the request
// Authentication is identified using the laravel_session cookie.
// If no authentication is present the request is halted.
func Authenticated(h ContextHandler) ContextHandler {
	return ContextHandlerFunc(func(ctx context.Context, rw http.ResponseWriter, req *http.Request) error {
		var db = ctx.Value(DBKey).(*sql.DB)

		var encryptedSessionID = ""
		for _, cookie := range req.Cookies() {
			if cookie.Name == "laravel_session" {
				encryptedSessionID = cookie.Value
			}
		}
		if encryptedSessionID == "" {
			return errors.New("Missing session cookie")
		}

		if sessionID, err := decrypt([]byte(encryptedSessionID)); err != nil {
			return err
		} else {
			if user, err := findUserByRememberToken(db, string(sessionID)); err != nil {
				return ErrAuthenticationRequired
			} else {
				ctx = context.WithValue(ctx, UserKey, &user)
				ctx = context.WithValue(ctx, UserStoreKey, &sqlUserStorage{db: db})
			}
		}

		return h.ServeHTTPContext(ctx, rw, req)
	})
}
示例#8
0
// After `ParseJSON`
func ParseHandle(allowEmpty bool) kami.Middleware {
	return func(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
		var h string
		_, exist := GetJSONKey(ctx, "handle")
		if !exist {
			if allowEmpty {
				newCtx := context.WithValue(ctx, keyHandleName, "")
				return context.WithValue(newCtx, keyHandle, nil)
			} else {
				WriteJSON(w, http.StatusBadRequest, BadField("handle"))
				return nil
			}
		}

		err := GetJSONKeyAs(ctx, "handle", &h)
		if err != nil {
			WriteJSON(w, http.StatusBadRequest, BadField("handle"))
			return nil
		}
		cli, err := client.GetHandle(h)
		if err != nil {
			WriteJSON(w, http.StatusBadRequest, UnknownHandle)
			return nil
		}
		newCtx := context.WithValue(ctx, keyHandleName, h)
		return context.WithValue(newCtx, keyHandle, cli)
	}
}
示例#9
0
func ParseAllTaskData(ctx context.Context, w http.ResponseWriter, r *http.Request) context.Context {
	session, err := store.Get(r, SessionName)
	if err != nil {
		log.Errorf("Frontend: Failed to save session: %s", err.Error())
		WriteJSON(w, http.StatusInternalServerError, InternalError)
		return nil
	}
	userid, ok := session.Values["user"]
	if !ok {
		WriteJSON(w, http.StatusUnauthorized, Unauthorized)
		return nil
	}
	handle, _ := session.Values["handle"]

	raw := manager.ListTasksData()
	if userid == *flagEdgeUser {
		return context.WithValue(ctx, keyAllTaskData, raw)
	} else {
		res := make([]icarus.TaskData, 0)
		for _, v := range raw {
			if v.User.UserID == userid && v.Handle == handle {
				res = append(res, v)
			}
		}
		return context.WithValue(ctx, keyAllTaskData, res)
	}
}
示例#10
0
func TestUserChangeEmail_HappyPath(t *testing.T) {
	var currentUser = dash.User{Username: "******"}
	var ctx = context.WithValue(rootCtx, UserKey, &currentUser)

	var mock = mockUserLoginStore{
		updateUserWithEmail: func(username, email string) error {
			if username != currentUser.Username {
				t.Errorf("Expected to update user %q but was %q", currentUser.Username, username)
			}
			if email != "*****@*****.**" {
				t.Errorf("Expected to update password to %q but was %q", "*****@*****.**", email)
			}
			return nil
		},
	}
	ctx = context.WithValue(ctx, UserStoreKey, &mock)

	req, _ := http.NewRequest("POST", "/users/change_email", strings.NewReader(`{"email":"*****@*****.**"}`))
	rw := httptest.NewRecorder()

	if err := UserChangeEmail(ctx, rw, req); err != nil {
		t.Fatalf("UserChangeEmail errored with: %#v", err)
	}
	var data map[string]string
	json.NewDecoder(rw.Body).Decode(&data)
	if data["status"] != "success" {
		t.Errorf("Expected status of %q to be %q", data["status"], "success")
	}
}
示例#11
0
// TestE2E verifies parent request IDs are properly set on child requests
func (suite *parentRequestIdMiddlewareSuite) TestE2E() {
	cli := client.
		NewClient().
		SetTransport(suite.trans).
		SetMiddleware([]client.ClientMiddleware{Middleware()})

	dummyOrigin := mercury.NewRequest()
	dummyOrigin.SetId("foobarbaz")
	ctx := context.WithValue(dummyOrigin.Context(), "Current-Service", testOriginServiceName)
	ctx = context.WithValue(ctx, "Current-Endpoint", "e2etest")
	dummyOrigin.SetContext(ctx)

	cli.Add(client.Call{
		Uid:      "call",
		Service:  testServiceName,
		Endpoint: "foo",
		Context:  dummyOrigin,
		Response: &testproto.DummyResponse{},
		Body:     &testproto.DummyRequest{}})
	cli.Execute()

	suite.Assert().NoError(cli.Errors().Combined())
	rsp := cli.Response("call")
	response := rsp.Body().(*testproto.DummyResponse)
	suite.Assert().NotEmpty(response.Pong)
	suite.Assert().Equal(response.Pong, rsp.Headers()[parentIdHeader])
}
示例#12
0
func TestUserLogout_HappyPath(t *testing.T) {
	var currentUser = dash.User{Username: "******"}
	var ctx = context.WithValue(rootCtx, UserKey, &currentUser)

	var mock = mockUserLoginStore{
		updateUserWithToken: func(username, token string) error {
			if username != currentUser.Username {
				t.Errorf("Expected to update user %q but was %q", currentUser.Username, username)
			}
			return nil
		},
	}
	ctx = context.WithValue(ctx, UserStoreKey, &mock)

	req, _ := http.NewRequest("POST", "/users/logout", strings.NewReader(``))
	rw := httptest.NewRecorder()

	if err := UserLogout(ctx, rw, req); err != nil {
		t.Fatalf("UserLogout errored with: %#v", err)
	}

	if !strings.Contains(rw.Header().Get("Set-Cookie"), "laravel_session=; Max-Age=0") {
		t.Errorf("Expected Set-Cookie header to contain %v", "laravel_session")
	}

	var data map[string]string
	json.NewDecoder(rw.Body).Decode(&data)
	if data["status"] != "success" {
		t.Errorf("Expected status of %q to be %q", data["status"], "success")
	}
}
示例#13
0
func main() {
	// context
	ctx = context.Background()
	db := initDb()
	ctx = context.WithValue(ctx, "test", "aaabbbccc")
	ctx = context.WithValue(ctx, "DB", db)

	// redis
	redis_pool := newPool()
	ctx = context.WithValue(ctx, "redis", redis_pool)

	str := ctx.Value("test")
	log.Println(str)

	api := rest.NewApi()
	api.Use(rest.DefaultDevStack...)
	router, err := rest.MakeRouter(
		rest.Post("/test", baseHandlerFunc(controller.Test)),
	)

	// 存在しないルート時
	if err != nil {
		log.Fatal(err)
	}

	api.SetApp(router)
	log.Fatal(http.ListenAndServe(":9999", api.MakeHandler()))
}
示例#14
0
func TestChainHandlerC(t *testing.T) {
	handlerCalls := 0
	h1 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			handlerCalls++
			ctx = context.WithValue(ctx, "test", 2)
			next.ServeHTTPC(ctx, w, r)
		})
	}

	c := Chain{}
	c.UseC(h1)
	c.UseC(h2)
	h := c.HandlerC(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		handlerCalls++

		assert.Equal(t, 2, ctx.Value("test"),
			"second handler should overwrite first handler's context value")
		assert.Equal(t, 1, ctx.Value("mainCtx"),
			"the mainCtx value should be pass through")
	}))

	mainCtx := context.WithValue(context.Background(), "mainCtx", 1)
	h.ServeHTTPC(mainCtx, nil, nil)

	assert.Equal(t, 3, handlerCalls, "all handler called once")
}
示例#15
0
func isAuthenticated(w http.ResponseWriter, r *http.Request, ctx context.Context) (context.Context, bool) {
	if ctx.Value(AccountKey) != nil {
		return ctx, true
	}

	application := ctx.Value(ApplicationKey).(*stormpath.Application)

	//Cookie
	authResult, ok := isCookieAuthenticated(r, application)
	if ok {
		saveAuthenticationResult(w, r, authResult, application)
		return context.WithValue(ctx, AccountKey, authResult.GetAccount()), ok
	}
	//Token
	tokenAuthResult, ok := isTokenBearerAuthenticated(r, application)
	if ok {
		saveAuthenticationResult(w, r, tokenAuthResult, application)
		return context.WithValue(ctx, AccountKey, tokenAuthResult.GetAccount()), ok
	}
	//Basic
	basicAuthResult, ok := isHTTPBasicAuthenticated(r, application)
	if ok {
		saveAuthenticationResult(w, r, basicAuthResult, application)
		return context.WithValue(ctx, AccountKey, basicAuthResult.GetAccount()), ok
	}

	clearAuthentication(w, r, application)
	return ctx, false
}
示例#16
0
func TestContext(t *testing.T) {
	w := New()
	w.Get("/", checkContext(t, "m1", "m1"))
	w.Use(func(next Handler) Handler {
		return func(c *Context) error {
			c.Context = context.WithValue(c.Context, "m1", "m1")
			return next(c)
		}
	})
	code, _ := doRequest(t, "GET", "/", nil, w)
	isHTTPStatusOK(t, code)

	w.Get("/some", checkContext(t, "m1", "m2"))
	w.Use(func(next Handler) Handler {
		return func(c *Context) error {
			c.Context = context.WithValue(c.Context, "m1", "m2")
			c.Response().WriteHeader(http.StatusBadRequest)
			return next(c)
		}
	})
	code, _ = doRequest(t, "GET", "/some", nil, w)
	if code != http.StatusBadRequest {
		t.Error("expecting %d, got %d", http.StatusBadRequest, code)
	}
}
示例#17
0
文件: zipkin.go 项目: zyanho/kit
// AnnotateClient returns a middleware that extracts a parent span from the
// context, produces a client (child) span from it, adds client-send and
// client-receive annotations at the boundaries, and submits the span to the
// collector. If no span is found in the context, a new span is generated and
// inserted.
func AnnotateClient(newSpan NewSpanFunc, c Collector) endpoint.Middleware {
	return func(next endpoint.Endpoint) endpoint.Endpoint {
		return func(ctx context.Context, request interface{}) (interface{}, error) {
			var clientSpan *Span
			parentSpan, ok := FromContext(ctx)
			if ok {
				clientSpan = newSpan(parentSpan.TraceID(), newID(), parentSpan.SpanID())
				clientSpan.runSampler = false
				clientSpan.sampled = c.ShouldSample(parentSpan)
			} else {
				// Abnormal operation. Traces should always start server side.
				// We create a root span but annotate with a warning.
				traceID := newID()
				clientSpan = newSpan(traceID, traceID, 0)
				c.ShouldSample(clientSpan)
				clientSpan.AnnotateBinary("warning", "missing server side trace")
			}
			ctx = context.WithValue(ctx, SpanContextKey, clientSpan)                    // set
			defer func() { ctx = context.WithValue(ctx, SpanContextKey, parentSpan) }() // reset
			clientSpan.Annotate(ClientSend)
			defer func() { clientSpan.Annotate(ClientReceive); c.Collect(clientSpan) }()
			return next(ctx, request)
		}
	}
}
示例#18
0
文件: main.go 项目: agupt/learn
func mainRun() {
	rootContext := context.Background()
	rootContext = context.WithValue(rootContext, odbKey, odb)
	rootContext = context.WithValue(rootContext, xdbKey, xdb)
	rootContext = context.WithValue(rootContext, rdbKey, rdb)
	rootContext = context.WithValue(rootContext, cdbKey, cdb)

	for {
		c, err := client.New(etcdClientConfig)
		if err != nil {
			panic(err)
		}
		kapi := client.NewKeysAPI(c)

		log.WithFields(log.Fields{
			"event_type": "run",
			"start_time": nowPacific(),
		}).Debugln("client.RunJobs running")

		if err := runJobs(rootContext, kapi); err != nil {
			log.WithFields(log.Fields{
				"event_type": "error",
				"error":      err,
			}).Errorln("client.RunJobs error")
		}

		time.Sleep(5 * time.Second)
	}
}
示例#19
0
func TestAppendHanlerC(t *testing.T) {
	init := 0
	h1 := func(next HandlerC) HandlerC {
		init++
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			ctx = context.WithValue(ctx, "test", 1)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	h2 := func(next HandlerC) HandlerC {
		return HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
			ctx = context.WithValue(ctx, "test", 2)
			next.ServeHTTPC(ctx, w, r)
		})
	}
	c := Chain{}
	c.UseC(h1)
	c.UseC(h2)
	assert.Len(t, c, 2)

	h := c.Handler(HandlerFuncC(func(ctx context.Context, w http.ResponseWriter, r *http.Request) {
		// Test ordering
		assert.Equal(t, 2, ctx.Value("test"), "second handler should overwrite first handler's context value")
	}))

	h.ServeHTTP(nil, nil)
	h.ServeHTTP(nil, nil)
	assert.Equal(t, 1, init, "handler init called once")
}
示例#20
0
// RotateKey supports only timestamp and snapshot key rotation
func TestRotateKeyEndpoint(t *testing.T) {
	ctx := context.WithValue(
		context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
	ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)

	ccc := utils.NewCacheControlConfig(10, false)
	handler := RootHandler(ctx, nil, signed.NewEd25519(), ccc, ccc, nil)
	ts := httptest.NewServer(handler)
	defer ts.Close()

	rolesToStatus := map[string]int{
		data.CanonicalTimestampRole: http.StatusOK,
		data.CanonicalSnapshotRole:  http.StatusOK,
		data.CanonicalTargetsRole:   http.StatusNotFound,
		data.CanonicalRootRole:      http.StatusNotFound,
		"targets/delegation":        http.StatusNotFound,
		"somerandomrole":            http.StatusNotFound,
	}
	var buf bytes.Buffer
	for role, expectedStatus := range rolesToStatus {
		res, err := http.Post(
			fmt.Sprintf("%s/v2/gun/_trust/tuf/%s.key", ts.URL, role),
			"text/plain", &buf)
		require.NoError(t, err)
		require.Equal(t, expectedStatus, res.StatusCode)
	}
}
示例#21
0
func TestAddNote(t *testing.T) {
	assert := assert.New(t)

	dbMap := initDb()
	defer dbMap.Db.Close()
	ctx := context.Background()
	ctx = context.WithValue(ctx, "db", dbMap)
	ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})

	server := httptest.NewServer(http.HandlerFunc(
		func(w http.ResponseWriter, r *http.Request) {
			AddNote(ctx, w, r)
		},
	))
	defer server.Close()

	resp := request(t, server.URL, http.StatusOK, map[string]interface{}{
		"title":   "Test Title",
		"content": "lorem ipsum dolor sit amet consetetur.",
		"ownerId": 0,
	})
	assert.NotNil(resp)

	note := resp.(map[string]interface{})
	assert.Equal("Test Title", note["title"])
	assert.Equal("lorem ipsum dolor sit amet consetetur.", note["content"])
	assert.EqualValues(0, note["ownerId"])
	assert.NotZero(note["createdAt"])
	assert.NotZero(note["updatedAt"])

	count, err := dbMap.SelectInt("SELECT COUNT(id) FROM notes")
	assert.Nil(err)
	assert.EqualValues(1, count)
}
示例#22
0
文件: mux.go 项目: vladdy/chi
func (mx *Mux) ServeHTTPC(ctx context.Context, w http.ResponseWriter, r *http.Request) {
	var cxh Handler
	var err error

	params, ok := ctx.Value(URLParamsCtxKey).(map[string]string)
	if !ok || params == nil {
		params = make(map[string]string, 0)
		ctx = context.WithValue(ctx, URLParamsCtxKey, params)
	}

	path := r.URL.Path
	if routePath, ok := ctx.Value(subRouterCtxKey).(string); ok {
		path = routePath
		ctx = context.WithValue(ctx, subRouterCtxKey, nil) // unset the routePath
		delete(params, "*")
	}

	routes := mx.routes[methodMap[r.Method]]
	cxh, err = routes.Find(path, params)
	_ = err // ..

	if cxh == nil {
		http.NotFound(w, r)
		return
	}

	// Serve it
	cxh.ServeHTTPC(ctx, w, r)
}
示例#23
0
func TestDeleteNote(t *testing.T) {
	assert := assert.New(t)

	dbMap := initDb()
	defer dbMap.Db.Close()
	ctx := context.Background()
	ctx = context.WithValue(ctx, "db", dbMap)
	ctx = context.WithValue(ctx, "auth", &auth.AuthContext{})

	dbMap.Insert(&model.Note{
		Id:        0,
		Title:     "Test Title 1",
		Content:   "lorem ipsum dolor sit amet consetetur.",
		OwnerId:   0,
		CreatedAt: 1442284669000,
		UpdatedAt: 1442292926000,
	})

	count, err := dbMap.SelectInt("SELECT COUNT(id) FROM notes")
	assert.Nil(err)
	assert.EqualValues(1, count)

	kami.Reset()
	kami.Context = ctx
	kami.Post("/api/notes/:noteId", DeleteNote)
	server := httptest.NewServer(kami.Handler())
	defer server.Close()

	request(t, server.URL+"/api/notes/1", http.StatusOK, nil)

	count, err = dbMap.SelectInt("SELECT COUNT(id) FROM notes")
	assert.Nil(err)
	assert.EqualValues(0, count)
}
示例#24
0
文件: engine.go 项目: byteslice/httpx
// ServeHTTP
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {

	handler := e.notFoundHandler
	handlers := make(Handlers)       // QUESTION: sync.Pool candidate?
	n, p := e.trie.match(r.URL.Path) // TODO: change method name to match

	if n != nil {
		if h, ok := n.handlers[r.Method]; ok {
			handler = h
		}
	}

	// Handlers needs to be copied, otherwise the map could
	// be mutated inside the subsequent calls
	// QUESTION: is this necessary?
	for k, v := range n.handlers {
		handlers[k] = v
	}

	// chain the middleware to construct a handler
	for i := len(n.engine.middleware) - 1; i >= 0; i-- {
		handler = n.engine.middleware[i].NextHTTP(handler)
	}

	// create the new context
	ctx := context.Background()
	ctx = context.WithValue(ctx, "httpx_params", p)
	ctx = context.WithValue(ctx, "httpx_handlers", handlers)

	// execute the chain by calling ServeHTTP on the constructed Handler
	handler.ServeHTTP(ctx, w, r)
}
示例#25
0
// Ensures that the httpstore can interpret the errors returned from the server
func TestValidationErrorFormat(t *testing.T) {
	ctx := context.WithValue(
		context.Background(), notary.CtxKeyMetaStore, storage.NewMemStorage())
	ctx = context.WithValue(ctx, notary.CtxKeyKeyAlgo, data.ED25519Key)

	handler := RootHandler(ctx, nil, signed.NewEd25519(), nil, nil, nil)
	server := httptest.NewServer(handler)
	defer server.Close()

	client, err := store.NewHTTPStore(
		fmt.Sprintf("%s/v2/docker.com/notary/_trust/tuf/", server.URL),
		"",
		"json",
		"key",
		http.DefaultTransport,
	)
	require.NoError(t, err)

	repo, _, err := testutils.EmptyRepo("docker.com/notary")
	require.NoError(t, err)
	r, tg, sn, ts, err := testutils.Sign(repo)
	require.NoError(t, err)
	rs, rt, _, _, err := testutils.Serialize(r, tg, sn, ts)
	require.NoError(t, err)

	// No snapshot is passed, and the server doesn't have the snapshot key,
	// so ErrBadHierarchy
	err = client.SetMulti(map[string][]byte{
		data.CanonicalRootRole:    rs,
		data.CanonicalTargetsRole: rt,
	})
	require.Error(t, err)
	require.IsType(t, validation.ErrBadHierarchy{}, err)
}
示例#26
0
// ServeHTTP serves an HTTP request and implements the http.Handler interface.
func (root *rootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	ctx := context.WithValue(root.context, "repo", vars["imageName"])

	ctx = context.WithValue(ctx, "cryptoService", root.trust)

	ctx = context.WithValue(ctx, "http.request", r)

	if root.auth != nil {
		var err error
		access := buildAccessRecords(vars["imageName"], root.actions...)
		if ctx, err = root.auth.Authorized(ctx, access...); err != nil {
			if err, ok := err.(auth.Challenge); ok {
				err.ServeHTTP(w, r)
				w.WriteHeader(http.StatusUnauthorized)
				return
			}
			errcode.ServeJSON(w, v2.ErrorCodeUnauthorized)
			return
		}
	}
	if err := root.handler(ctx, w, r); err != nil {
		logrus.Error("[Notary Server] ", err.Error())
		e := errcode.ServeJSON(w, err)
		if e != nil {
			logrus.Error(e)
		}
		return
	}
	return
}
示例#27
0
文件: fs.go 项目: keybase/kbfs-beta
// WithContext adds app- and request-specific values to the context.
// It is called by FUSE for normal runs, but may be called explicitly
// in other settings, such as tests.
func (f *FS) WithContext(ctx context.Context) context.Context {
	ctx = context.WithValue(ctx, CtxAppIDKey, f)
	logTags := make(logger.CtxLogTags)
	logTags[CtxIDKey] = CtxOpID
	ctx = logger.NewContextWithLogTags(ctx, logTags)

	// Add a unique ID to this context, identifying a particular
	// request.
	id, err := libkbfs.MakeRandomRequestID()
	if err != nil {
		f.log.Errorf("Couldn't make request ID: %v", err)
	} else {
		ctx = context.WithValue(ctx, CtxIDKey, id)
	}

	if runtime.GOOS == "darwin" {
		// Timeout operations before they hit the osxfuse time limit,
		// so we don't hose the entire mount (Fixed in OSXFUSE 3.2.0).
		// The timeout is 60 seconds, but it looks like sometimes it
		// tries multiple attempts within that 60 seconds, so let's go
		// a little under 60/3 to be safe.
		//
		// It should be safe to ignore the CancelFunc here because our
		// parent context will be canceled by the FUSE serve loop.
		ctx, _ = context.WithTimeout(ctx, 19*time.Second)
	}

	return ctx
}
示例#28
0
文件: keys_test.go 项目: cyli/notary
// initialize a repo with keys, so they can be rotated
func setUpRepo(t *testing.T, tempBaseDir, gun string, ret notary.PassRetriever) (
	*httptest.Server, map[string]string) {

	// Set up server
	ctx := context.WithValue(
		context.Background(), "metaStore", storage.NewMemStorage())

	// Do not pass one of the const KeyAlgorithms here as the value! Passing a
	// string is in itself good test that we are handling it correctly as we
	// will be receiving a string from the configuration.
	ctx = context.WithValue(ctx, "keyAlgorithm", "ecdsa")

	// Eat the logs instead of spewing them out
	l := logrus.New()
	l.Out = bytes.NewBuffer(nil)
	ctx = ctxu.WithLogger(ctx, logrus.NewEntry(l))

	cryptoService := cryptoservice.NewCryptoService(trustmanager.NewKeyMemoryStore(ret))
	ts := httptest.NewServer(server.RootHandler(nil, ctx, cryptoService, nil, nil, nil))

	repo, err := client.NewNotaryRepository(
		tempBaseDir, gun, ts.URL, http.DefaultTransport, ret, trustpinning.TrustPinConfig{})
	require.NoError(t, err, "error creating repo: %s", err)

	rootPubKey, err := repo.CryptoService.Create("root", "", data.ECDSAKey)
	require.NoError(t, err, "error generating root key: %s", err)

	err = repo.Initialize(rootPubKey.ID())
	require.NoError(t, err)

	return ts, repo.CryptoService.ListAllKeys()
}
示例#29
0
文件: http.go 项目: rogaha/notary
// ServeHTTP serves an HTTP request and implements the http.Handler interface.
func (root *rootHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)
	ctx := ctxu.WithRequest(root.context, r)
	ctx, w = ctxu.WithResponseWriter(ctx, w)
	ctx = ctxu.WithLogger(ctx, ctxu.GetRequestLogger(ctx))
	ctx = context.WithValue(ctx, "repo", vars["imageName"])
	ctx = context.WithValue(ctx, "cryptoService", root.trust)

	defer func() {
		ctxu.GetResponseLogger(ctx).Info("response completed")
	}()

	if root.auth != nil {
		access := buildAccessRecords(vars["imageName"], root.actions...)
		var authCtx context.Context
		var err error
		if authCtx, err = root.auth.Authorized(ctx, access...); err != nil {
			if err, ok := err.(auth.Challenge); ok {
				err.ServeHTTP(w, r)
				w.WriteHeader(http.StatusUnauthorized)
				return
			}
			errcode.ServeJSON(w, v2.ErrorCodeUnauthorized)
			return
		}
		ctx = authCtx
	}
	if err := root.handler(ctx, w, r); err != nil {
		e := errcode.ServeJSON(w, err)
		if e != nil {
			logrus.Error(e)
		}
		return
	}
}
示例#30
0
func ContextValues() (ctx context.Context) {
	ctx = context.Background()
	ctx = context.WithValue(ctx, "db", Database())
	ctx = context.WithValue(ctx, "email", EmailSetup())

	return ctx
}