Skip to content
Myr

feat: add SecureJSON func to prevent json hijacking

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Eason Lin · committed by Eason Lin · parent 0c3726b · Browse files · 6 files+101 added−9 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+101 added−9 removed

  • other:+101 added−9 removed

6 files+101 added−9 removed

modified:render/json.go+26 added
3 unmodified lines
45package render67import (8 "bytes"9 "encoding/json"10 "net/http"11)12
4 unmodified lines
17type IndentedJSON struct {18 Data interface{}19}2021type SecureJSON struct {22 Prefix string23 Data interface{}24}2526type SecureJSONPrefix string2728var jsonContentType = []string{"application/json; charset=utf-8"}2930func (r JSON) Render(w http.ResponseWriter) (err error) {31 if err = WriteJSON(w, r.Data); err != nil {
28 unmodified lines
6061func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {62 writeContentType(w, jsonContentType)63}6465func (r SecureJSON) Render(w http.ResponseWriter) error {66 r.WriteContentType(w)67 jsonBytes, err := json.Marshal(r.Data)68 if err != nil {69 return err70 }71 // if the jsonBytes is array values72 if bytes.HasPrefix(jsonBytes, []byte("[")) && bytes.HasSuffix(jsonBytes, []byte("]")) {73 w.Write([]byte(r.Prefix))74 }75 w.Write(jsonBytes)76 return nil77}7879func (r SecureJSON) WriteContentType(w http.ResponseWriter) {80 writeContentType(w, jsonContentType)81}
modified:render/render_test.go+25 added
64 unmodified lines
65 assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\"\n}")66 assert.Equal(t, w.Header().Get("Content-Type"), "application/json; charset=utf-8")67}6869func TestRenderSecureJSON(t *testing.T) {70 w1 := httptest.NewRecorder()71 data := map[string]interface{}{72 "foo": "bar",73 }7475 err1 := (SecureJSON{"while(1);", data}).Render(w1)7677 assert.NoError(t, err1)78 assert.Equal(t, "{\"foo\":\"bar\"}", w1.Body.String())79 assert.Equal(t, "application/json; charset=utf-8", w1.Header().Get("Content-Type"))8081 w2 := httptest.NewRecorder()82 datas := []map[string]interface{}{{83 "foo": "bar",84 }, {85 "bar": "foo",86 }}8788 err2 := (SecureJSON{"while(1);", datas}).Render(w2)89 assert.NoError(t, err2)90 assert.Equal(t, "while(1);[{\"foo\":\"bar\"},{\"bar\":\"foo\"}]", w2.Body.String())91 assert.Equal(t, "application/json; charset=utf-8", w2.Header().Get("Content-Type"))92}9394type xmlmap map[string]interface{}9596// Allows type H to be used with xml.Marshal97func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
81 unmodified lines
modified:render/render.go+1 added
12 unmodified lines
1314var (15 _ Render = JSON{}16 _ Render = IndentedJSON{}17 _ Render = SecureJSON{}18 _ Render = XML{}19 _ Render = String{}20 _ Render = Redirect{}21 _ Render = Data{}
14 unmodified lines
modified:context_test.go+26 added
596 unmodified lines
597 assert.Equal(t, "", w.Body.String())598 assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")599}600601// Tests that the response is serialized as Secure JSON602// and Content-Type is set to application/json603func TestContextRenderSecureJSON(t *testing.T) {604 w := httptest.NewRecorder()605 c, router := CreateTestContext(w)606607 router.SecureJsonPrefix("&&&START&&&")608 c.SecureJSON(201, []string{"foo", "bar"})609610 assert.Equal(t, w.Code, 201)611 assert.Equal(t, w.Body.String(), "&&&START&&&[\"foo\",\"bar\"]")612 assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")613}614615// Tests that no Custom JSON is rendered if code is 204616func TestContextRenderNoContentSecureJSON(t *testing.T) {617 w := httptest.NewRecorder()618 c, _ := CreateTestContext(w)619620 c.SecureJSON(204, []string{"foo", "bar"})621622 assert.Equal(t, 204, w.Code)623 assert.Equal(t, "", w.Body.String())624 assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")625}626627// Tests that the response executes the templates628// and responds with Content-Type set to text/html629func TestContextRenderHTML(t *testing.T) {630 w := httptest.NewRecorder()
594 unmodified lines
modified:context.go+7 added
614 unmodified lines
615func (c *Context) IndentedJSON(code int, obj interface{}) {616 c.Render(code, render.IndentedJSON{Data: obj})617}618619// SecureJSON serializes the given struct as Secure JSON into the response body.620// Default prepends "while(1)," to response body if the given struct is array values.621// It also sets the Content-Type as "application/json".622func (c *Context) SecureJSON(code int, obj interface{}) {623 c.Render(code, render.SecureJSON{Prefix: c.engine.secureJsonPrefix, Data: obj})624}625626// JSON serializes the given struct as JSON into the response body.627// It also sets the Content-Type as "application/json".628func (c *Context) JSON(code int, obj interface{}) {629 c.Render(code, render.JSON{Data: obj})
146 unmodified lines
modified:gin.go+16 added-9 removed
42 unmodified lines
43// Engine is the framework's instance, it contains the muxer, middleware and configuration settings.44// Create an instance of Engine, by using New() or Default()45type Engine struct {46 RouterGroup47 delims render.Delims47 delims render.Delims48 HTMLRender render.HTMLRender49 FuncMap template.FuncMap50 allNoRoute HandlersChain51 allNoMethod HandlersChain52 noRoute HandlersChain53 noMethod HandlersChain54 pool sync.Pool55 trees methodTrees48 secureJsonPrefix string49 HTMLRender render.HTMLRender50 FuncMap template.FuncMap51 allNoRoute HandlersChain52 allNoMethod HandlersChain53 noRoute HandlersChain54 noMethod HandlersChain55 pool sync.Pool56 trees methodTrees5758 // Enables automatic redirection if the current route can't be matched but a59 // handler for the path with (without) the trailing slash exists.60 // For example if /foo/ is requested but a route only exists for /foo, the
60 unmodified lines
121 UseRawPath: false,122 UnescapePathValues: true,123 trees: make(methodTrees, 0, 9),124 delims: render.Delims{"{{", "}}"},125 secureJsonPrefix: "while(1);",126 }127 engine.RouterGroup.engine = engine128 engine.pool.New = func() interface{} {129 return engine.allocateContext()
16 unmodified lines
146 engine.delims = render.Delims{left, right}147 return engine148}149150func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {151 engine.secureJsonPrefix = prefix152 return engine153}154155func (engine *Engine) LoadHTMLGlob(pattern string) {156 if IsDebugging() {157 debugPrintLoadTemplate(template.Must(template.New("").Delims(engine.delims.Left, engine.delims.Right).Funcs(engine.FuncMap).ParseGlob(pattern)))158 engine.HTMLRender = render.HTMLDebug{Glob: pattern, FuncMap: engine.FuncMap, Delims: engine.delims}
264 unmodified lines