Skip to content

Commit

Permalink
Secure POST /report via basic auth
Browse files Browse the repository at this point in the history
  • Loading branch information
tvrg committed Jun 17, 2022
1 parent 164ec61 commit 658bf80
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
36 changes: 32 additions & 4 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (
"github.com/labstack/echo/v4/middleware"
)

func New(db *sqlx.DB) *echo.Echo {
func New(db *sqlx.DB, token string) *echo.Echo {
app := echo.New()
app.Use(middleware.Recover())
app.HTTPErrorHandler = func(err error, c echo.Context) {
Expand All @@ -28,9 +28,14 @@ func New(db *sqlx.DB) *echo.Echo {
})
}

wrapper := ServerInterfaceWrapper{Handler: &api{db: db}}
wrapper := ServerInterfaceWrapper{
Handler: &api{
db: db,
token: token,
},
}

app.POST("/report/:commit", wrapper.AddReport)
app.POST("/report/:commit", secure(token, wrapper.AddReport))
app.GET("/flakes", wrapper.GetFlakyTests)

spec, err := GetSwagger()
Expand All @@ -42,6 +47,29 @@ func New(db *sqlx.DB) *echo.Echo {
return app
}


func secure(token string, handler echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user, pass, ok := c.Request().BasicAuth()

if !ok {
return unauthorized(c, "noflake", "no credentials provided")
}

if user != "token" || pass != token{
return unauthorized(c, "noflake", "wrong credentials")
}

return handler(c)
}
}

func unauthorized(c echo.Context, realm, reason string) error {
c.Response().Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
return echo.NewHTTPError(http.StatusUnauthorized, reason)
}

type api struct {
db *sqlx.DB
db *sqlx.DB
token string
}
9 changes: 8 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,17 @@ func main() {
EnvVars: []string{"NOFLAKE_DB"},
Value: "noflake.sqlite3",
},
&cli.StringFlag{
Name: "token",
Usage: "token to secure the POST endpoints",
EnvVars: []string{"NOFLAKE_TOKEN"},
Required: true,
},
},
Action: func(c *cli.Context) error {
db := database.New(c.String("db"))
webapi := api.New(db)
token := c.String("token")
webapi := api.New(db, token)

listenAddr := c.String("address")
log.Info().Str("address", listenAddr).Msg("HTTP")
Expand Down

0 comments on commit 658bf80

Please sign in to comment.