Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor http responses #46

Merged
merged 3 commits into from
Mar 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
253 changes: 63 additions & 190 deletions admin/handlers-post.go

Large diffs are not rendered by default.

21 changes: 9 additions & 12 deletions admin/handlers-tokens.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import (
"github.com/jmpsec/osctrl/utils"
)

const (
metricTokenReq = "admin-token-req"
metricTokenErr = "admin-token-err"
metricTokenOK = "admin-token-ok"
)

// TokenJSON to be used to populate a JSON token
type TokenJSON struct {
Token string `json:"token"`
Expand Down Expand Up @@ -52,17 +58,8 @@ func tokensGETHandler(w http.ResponseWriter, r *http.Request) {
ExpiresTS: user.TokenExpire.String(),
}
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
log.Printf("error serializing JSON %v", err)
incMetric(metricTokenErr)
return
}
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricTokenOK)
}

Expand Down Expand Up @@ -131,6 +128,6 @@ func tokensPOSTHandler(w http.ResponseWriter, r *http.Request) {
return
}
// Serialize and serve JSON
apiHTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, response)
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, response)
incMetric(metricTokenOK)
}
20 changes: 6 additions & 14 deletions admin/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,48 +8,40 @@ import (
)

const (
metricAdminReq = "admin-req"
metricAdminErr = "admin-err"
metricAdminOK = "admin-ok"
metricJSONReq = "admin-json-req"
metricJSONErr = "admin-json-err"
metricJSONOK = "admin-json-ok"
metricTokenReq = "admin-token-req"
metricTokenErr = "admin-token-err"
metricTokenOK = "admin-token-ok"
metricHealthReq = "health-req"
metricHealthOK = "health-ok"
)

// Empty default osquery configuration
const emptyConfiguration string = "data/osquery-empty.json"

const errorContent = "❌"
const okContent = "✅"

// Handle health requests
func healthHTTPHandler(w http.ResponseWriter, r *http.Request) {
incMetric(metricHealthReq)
utils.DebugHTTPDump(r, settingsmgr.DebugHTTP(settings.ServiceAdmin), true)
// Send response
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("✅"))
utils.HTTPResponse(w, "", http.StatusOK, okContent)
incMetric(metricHealthOK)
}

// Handle error requests
func errorHTTPHandler(w http.ResponseWriter, r *http.Request) {
utils.DebugHTTPDump(r, settingsmgr.DebugHTTP(settings.ServiceAdmin), true)
// Send response
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte("oh no..."))
utils.HTTPResponse(w, "", http.StatusInternalServerError, []byte("oh no..."))
}

// Handle forbidden error requests
func forbiddenHTTPHandler(w http.ResponseWriter, r *http.Request) {
utils.DebugHTTPDump(r, settingsmgr.DebugHTTP(settings.ServiceAdmin), true)
// Send response
w.WriteHeader(http.StatusForbidden)
_, _ = w.Write([]byte("❌"))
utils.HTTPResponse(w, "", http.StatusForbidden, errorContent)
}

// Handler for the favicon
Expand Down
25 changes: 5 additions & 20 deletions admin/json-carves.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"encoding/json"
"log"
"net/http"

Expand Down Expand Up @@ -66,24 +65,21 @@ func jsonCarvesHandler(w http.ResponseWriter, r *http.Request) {
// Extract target
target, ok := vars["target"]
if !ok {
incMetric(metricAdminErr)
log.Println("error getting target")
incMetric(metricJSONErr)
log.Println("error getting target")
return
}
// Verify target
if !CarvesTargets[target] {
incMetric(metricAdminErr)
log.Printf("invalid target %s", target)
incMetric(metricJSONErr)
log.Printf("invalid target %s", target)
return
}
// Retrieve carves for that target
qs, err := queriesmgr.GetCarves(target)
if err != nil {
incMetric(metricAdminErr)
log.Printf("error getting query carves %v", err)
incMetric(metricJSONErr)
log.Printf("error getting query carves %v", err)
return
}
// Prepare data to be returned
Expand Down Expand Up @@ -137,18 +133,7 @@ func jsonCarvesHandler(w http.ResponseWriter, r *http.Request) {
returned := ReturnedCarves{
Data: cJSON,
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
incMetric(metricAdminErr)
log.Printf("error serializing JSON %v", err)
incMetric(metricJSONErr)
return
}
incMetric(metricAdminOK)
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricJSONOK)
}
29 changes: 4 additions & 25 deletions admin/json-logs.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"encoding/json"
"log"
"net/http"
"strconv"
Expand Down Expand Up @@ -142,18 +141,8 @@ func jsonLogsHandler(w http.ResponseWriter, r *http.Request) {
returned := ReturnedLogs{
Data: logJSON,
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
log.Printf("error serializing JSON %v", err)
incMetric(metricJSONErr)
return
}
incMetric(metricAdminOK)
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serialize and serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricJSONOK)
}

Expand Down Expand Up @@ -193,17 +182,7 @@ func jsonQueryLogsHandler(w http.ResponseWriter, r *http.Request) {
returned := ReturnedQueryLogs{
Data: queryLogJSON,
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
log.Printf("error serializing JSON %v", err)
incMetric(metricJSONErr)
return
}
incMetric(metricAdminOK)
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serialize and serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricJSONOK)
}
27 changes: 4 additions & 23 deletions admin/json-nodes.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"encoding/json"
"log"
"net/http"

Expand Down Expand Up @@ -95,17 +94,8 @@ func jsonEnvironmentHandler(w http.ResponseWriter, r *http.Request) {
returned := ReturnedNodes{
Data: nJSON,
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
log.Printf("error serializing JSON %v", err)
incMetric(metricJSONErr)
return
}
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricJSONOK)
}

Expand Down Expand Up @@ -161,16 +151,7 @@ func jsonPlatformHandler(w http.ResponseWriter, r *http.Request) {
returned := ReturnedNodes{
Data: nJSON,
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
log.Printf("error serializing JSON %v", err)
incMetric(metricJSONErr)
return
}
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricJSONOK)
}
14 changes: 2 additions & 12 deletions admin/json-queries.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"encoding/json"
"log"
"net/http"

Expand Down Expand Up @@ -126,16 +125,7 @@ func jsonQueryHandler(w http.ResponseWriter, r *http.Request) {
returned := ReturnedQueries{
Data: qJSON,
}
// Serialize JSON
returnedJSON, err := json.Marshal(returned)
if err != nil {
log.Printf("error serializing JSON %v", err)
incMetric(metricJSONErr)
return
}
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, returned)
incMetric(metricJSONOK)
}
16 changes: 3 additions & 13 deletions admin/json-stats.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package main

import (
"encoding/json"
"log"
"net/http"

Expand Down Expand Up @@ -62,16 +61,7 @@ func jsonStatsHandler(w http.ResponseWriter, r *http.Request) {
return
}
}
// Serialize JSON
returnedJSON, err := json.Marshal(stats)
if err != nil {
incMetric(metricAdminErr)
log.Printf("error serializing JSON %v", err)
return
}
incMetric(metricAdminOK)
// Header to serve JSON
w.Header().Set(utils.ContentType, utils.JSONApplicationUTF8)
w.WriteHeader(http.StatusOK)
_, _ = w.Write(returnedJSON)
// Serve JSON
utils.HTTPResponse(w, utils.JSONApplicationUTF8, http.StatusOK, stats)
incMetric(metricJSONOK)
}
2 changes: 1 addition & 1 deletion admin/templates/carves.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

<div class="card mt-2">
<div class="card-header">
<i class="nav-icon fas fa-terminal"></i> {{ .Title }}
<i class="nav-icon fas fa-archive"></i> {{ .Title }}
<div class="card-header-actions">
<button class="btn btn-sm btn-outline-primary" data-tooltip="true"
data-placement="bottom" title="Refresh table" onclick="refreshTableNow('tableCarves');">
Expand Down
4 changes: 2 additions & 2 deletions admin/templates/components/page-aside-left.html
Original file line number Diff line number Diff line change
Expand Up @@ -230,12 +230,12 @@
<li class="nav-title">On-Demand Queries</li>
<li class="nav-item">
<a class="nav-link" href="/query/run">
<i class="nav-icon fas fa-terminal"></i> Run Query
<i class="nav-icon fab fa-searchengin"></i> Run Query
</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/query/list">
<i class="nav-icon fab fa-searchengin"></i> All Queries
<i class="nav-icon fas fa-list"></i> All Queries
</a>
</li>

Expand Down
2 changes: 1 addition & 1 deletion admin/templates/node.html
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
</button>
<button type="button" class="btn custom-size-btn btn-outline-dark"
data-tooltip="true" data-placement="top" title="Run Query" onclick="showQueryNodes([{{ .UUID }}]);">
<i class="fas fa-terminal"></i>
<i class="fab fa-searchengin"></i>
</button>
<button type="button" class="btn custom-size-btn btn-outline-info"
data-tooltip="true" data-placement="top" title="Carve File" onclick="showCarveFiles([{{ .UUID }}]);">
Expand Down
4 changes: 2 additions & 2 deletions admin/templates/queries-run.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

<div class="card mt-2">
<div class="card-header">
<i class="nav-icon fas fa-terminal"></i> Run on-demand queries by target
<i class="fab fa-searchengin"></i> Run on-demand queries by target
</div>
<div class="card-body">

Expand Down Expand Up @@ -163,7 +163,7 @@
<div class="col-sm-6 mx-auto">
<button id="query_button" type="button" class="btn btn-sm btn-outline-dark"
data-tooltip="true" data-placement="top" title="Send query" onclick="sendQuery();">
<i class="fas fa-search"></i> Query
<i class="fab fa-searchengin"></i> Query
</button>
</div>
<div class="col-sm-6 mx-auto">
Expand Down
2 changes: 1 addition & 1 deletion admin/templates/queries.html
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

<div class="card mt-2">
<div class="card-header">
<i class="nav-icon fas fa-terminal"></i> {{ .Title }}
<i class="nav-icon fab fa-searchengin"></i> {{ .Title }}
<div class="card-header-actions">
<button class="btn btn-sm btn-outline-primary" data-tooltip="true"
data-placement="bottom" title="Refresh table" onclick="refreshTableNow('tableQueries');">
Expand Down
2 changes: 1 addition & 1 deletion admin/templates/table.html
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@
},
{
className: 'btn custom-size-btn btn-outline-dark',
text: '<i class="fa fa-terminal"></i>',
text: '<i class="fab fa-searchengin"></i>',
titleAttr: 'Run Query',
attr: {
'data-toggle': 'tooltip',
Expand Down
17 changes: 1 addition & 16 deletions admin/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -398,23 +398,8 @@ func templateMetadata(ctx contextValue, service, version string) TemplateMetadat
}
}

// Helper to send HTTP response
func apiHTTPResponse(w http.ResponseWriter, cType string, code int, data interface{}) {
if cType != "" {
w.Header().Set(utils.ContentType, cType)
}
content, err := json.Marshal(data)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("error serializing response: %v", err)
content = []byte("error serializing response")
}
w.WriteHeader(code)
_, _ = w.Write(content)
}

// Helper to handle admin error responses
func adminErrorResponse(w http.ResponseWriter, msg string, code int, err error) {
log.Printf("%s: %v", msg, err)
apiHTTPResponse(w, utils.JSONApplicationUTF8, code, AdminResponse{Message: msg})
utils.HTTPResponse(w, utils.JSONApplicationUTF8, code, AdminResponse{Message: msg})
}
Loading