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
Provenance
- Commit
75ed286- Tree
b6a7f78- Author
Eason Lin <easonlin404@gmail.com>- Committer
Eason Lin <easonlin404@gmail.com>- Parent
0c3726b
6 files changed+101 added−9 removed
modified:render/json.go+26 added
3 unmodified lines4 5 package render6 7 import (8+ "bytes"9 "encoding/json"10 "net/http"11 )12 4 unmodified lines17 type IndentedJSON struct {18 Data interface{}19 }20 21+type SecureJSON struct {22+ Prefix string23+ Data interface{}24+}25+26+type SecureJSONPrefix string27+28 var jsonContentType = []string{"application/json; charset=utf-8"}29 30 func (r JSON) Render(w http.ResponseWriter) (err error) {31 if err = WriteJSON(w, r.Data); err != nil {28 unmodified lines60 61 func (r IndentedJSON) WriteContentType(w http.ResponseWriter) {62 writeContentType(w, jsonContentType)63 }64+65+func (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+}78+79+func (r SecureJSON) WriteContentType(w http.ResponseWriter) {80+ writeContentType(w, jsonContentType)81+}modified:render/render_test.go+25 added
64 unmodified lines65 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 }68 69+func TestRenderSecureJSON(t *testing.T) {70+ w1 := httptest.NewRecorder()71+ data := map[string]interface{}{72+ "foo": "bar",73+ }74+75+ err1 := (SecureJSON{"while(1);", data}).Render(w1)76+77+ 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"))80+81+ w2 := httptest.NewRecorder()82+ datas := []map[string]interface{}{{83+ "foo": "bar",84+ }, {85+ "bar": "foo",86+ }}87+88+ 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+}93+94 type xmlmap map[string]interface{}95 96 // Allows type H to be used with xml.Marshal97 func (h xmlmap) MarshalXML(e *xml.Encoder, start xml.StartElement) error {81 unmodified linesmodified:render/render.go+1 added
12 unmodified lines13 14 var (15 _ Render = JSON{}16 _ Render = IndentedJSON{}17+ _ Render = SecureJSON{}18 _ Render = XML{}19 _ Render = String{}20 _ Render = Redirect{}21 _ Render = Data{}14 unmodified linesmodified:context_test.go+26 added
596 unmodified lines597 assert.Equal(t, "", w.Body.String())598 assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")599 }600 601+// Tests that the response is serialized as Secure JSON602+// and Content-Type is set to application/json603+func TestContextRenderSecureJSON(t *testing.T) {604+ w := httptest.NewRecorder()605+ c, router := CreateTestContext(w)606+607+ router.SecureJsonPrefix("&&&START&&&")608+ c.SecureJSON(201, []string{"foo", "bar"})609+610+ 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+}614+615+// Tests that no Custom JSON is rendered if code is 204616+func TestContextRenderNoContentSecureJSON(t *testing.T) {617+ w := httptest.NewRecorder()618+ c, _ := CreateTestContext(w)619+620+ c.SecureJSON(204, []string{"foo", "bar"})621+622+ 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+}626+627 // Tests that the response executes the templates628 // and responds with Content-Type set to text/html629 func TestContextRenderHTML(t *testing.T) {630 w := httptest.NewRecorder()594 unmodified linesmodified:context.go+7 added
614 unmodified lines615 func (c *Context) IndentedJSON(code int, obj interface{}) {616 c.Render(code, render.IndentedJSON{Data: obj})617 }618 619+// 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".622+func (c *Context) SecureJSON(code int, obj interface{}) {623+ c.Render(code, render.SecureJSON{Prefix: c.engine.secureJsonPrefix, Data: obj})624+}625+626 // JSON serializes the given struct as JSON into the response body.627 // It also sets the Content-Type as "application/json".628 func (c *Context) JSON(code int, obj interface{}) {629 c.Render(code, render.JSON{Data: obj})146 unmodified linesmodified:gin.go+16 added-9 removed
42 unmodified lines43 // 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()45 type 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 methodTrees57 58 // 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, the60 unmodified lines121 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 lines146 engine.delims = render.Delims{left, right}147 return engine148 }149 150+func (engine *Engine) SecureJsonPrefix(prefix string) *Engine {151+ engine.secureJsonPrefix = prefix152+ return engine153+}154+155 func (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