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

Don't autogenerate access token on homepage. #8

Closed
wants to merge 7 commits into from
Closed
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
6 changes: 5 additions & 1 deletion cmd/scrape-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ var (
dbFlags *cmd.DatabaseFlags
headlessEnabled *envflags.Value[bool]
profile *envflags.Value[bool]
publicHome *envflags.Value[bool]
logWriter io.Writer
)

Expand Down Expand Up @@ -77,7 +78,7 @@ func main() {
slog.Info("scrape-server authorization is disabled, running in open access mode")
}

mux, err := server.InitMux(ss, dbh)
mux, err := server.InitMux(ss, dbh, publicHome.Get())
if err != nil {
slog.Error("scrape-server error initializing the server's mux", "error", err)
os.Exit(1)
Expand Down Expand Up @@ -137,6 +138,9 @@ func init() {
profile = envflags.NewBool("PROFILE", false)
profile.AddTo(&flags, "profile", "Enable profiling at /debug/pprof")

publicHome = envflags.NewBool("PUBLIC_HOME", false)
publicHome.AddTo(&flags, "public-home", "Enable the homepage without requiring a token (when auth is enabled)")

logLevel := envflags.NewLogLevel("LOG_LEVEL", slog.LevelInfo)
logLevel.AddTo(&flags, "log-level", "Set the log level [debug|error|info|warn]")
flags.Parse(os.Args[1:])
Expand Down
23 changes: 16 additions & 7 deletions internal/server/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,20 @@ import (
//go:embed templates/index.html
var home embed.FS

func mustHomeTemplate(ss *scrapeServer) *template.Template {
// mustHomeTemplate creates a template for the home page.
// To enable usage of the home page without a token when auth is enabled,
// for API endpoint, set openHome to true.
func mustHomeTemplate(ss *scrapeServer, openHome bool) *template.Template {
tmpl := template.New("home")
var authTokenF = func() string { return "" }
var authEnabledF = func() bool { return ss.AuthEnabled() }
if authEnabledF() {
var showTokenWidget = func() bool {
// when openHome is true don't show the token entry widget
if openHome {
return false
}
return ss.AuthEnabled()
}
if ss.AuthEnabled() && openHome {
authTokenF = func() string {
c, err := auth.NewClaims(
auth.WithSubject("home"),
Expand All @@ -37,17 +46,17 @@ func mustHomeTemplate(ss *scrapeServer) *template.Template {
}
}
funcMap := template.FuncMap{
"AuthToken": authTokenF,
"AuthEnabled": authEnabledF,
"AuthToken": authTokenF,
"ShowTokenWidget": showTokenWidget,
}
tmpl = tmpl.Funcs(funcMap)
homeSource, _ := home.ReadFile("templates/index.html")
tmpl = template.Must(tmpl.Parse(string(homeSource)))
return tmpl
}

func homeHandler(ss *scrapeServer) http.HandlerFunc {
tmpl := mustHomeTemplate(ss)
func homeHandler(ss *scrapeServer, openHome bool) http.HandlerFunc {
tmpl := mustHomeTemplate(ss, openHome)
return func(w http.ResponseWriter, r *http.Request) {
var buf bytes.Buffer
if err := tmpl.Execute(&buf, nil); err != nil {
Expand Down
16 changes: 13 additions & 3 deletions internal/server/home_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,31 @@ func TestMustTemplate(t *testing.T) {
tests := []struct {
name string
key auth.HMACBase64Key
openHome bool
expectToken bool
}{
{
name: "with key",
name: "auth enabled",
key: auth.MustNewHS256SigningKey(),
openHome: false,
expectToken: false,
},
{
name: "auth enabled with open home",
key: auth.MustNewHS256SigningKey(),
openHome: true,
expectToken: true,
},
{
name: "no key",
name: "auth disabled",
key: nil,
openHome: false,
expectToken: false,
},
{
name: "empty key",
key: auth.HMACBase64Key([]byte{}),
openHome: false,
expectToken: false,
},
}
Expand All @@ -36,7 +46,7 @@ func TestMustTemplate(t *testing.T) {
WithURLFetcher(&mockUrlFetcher{}),
WithAuthorizationIf(test.key),
)
tmpl := mustHomeTemplate(ss)
tmpl := mustHomeTemplate(ss, test.openHome)
tmpl, err := tmpl.Parse("{{AuthToken}}")
if err != nil {
t.Fatalf("[%s] Error parsing template: %s", test.name, err)
Expand Down
14 changes: 7 additions & 7 deletions internal/server/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ import (
"github.com/efixler/scrape/internal/server/healthchecks"
)

func InitMux(scrapeServer *scrapeServer, db *database.DBHandle) (*http.ServeMux, error) {
func InitMux(ss *scrapeServer, db *database.DBHandle, openHome bool) (*http.ServeMux, error) {
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", homeHandler(scrapeServer))
mux.HandleFunc("GET /{$}", homeHandler(ss, openHome))
mux.Handle("/assets/", assetsHandler())
h := scrapeServer.singleHandler()
h := ss.singleHandler()
mux.HandleFunc("GET /extract", h)
mux.HandleFunc("POST /extract", h)
h = scrapeServer.singleHeadlessHandler()
h = ss.singleHeadlessHandler()
mux.HandleFunc("GET /extract/headless", h)
mux.HandleFunc("POST /extract/headless", h)
mux.HandleFunc("POST /batch", scrapeServer.batchHandler())
mux.HandleFunc("DELETE /extract", scrapeServer.deleteHandler())
h = scrapeServer.feedHandler()
mux.HandleFunc("POST /batch", ss.batchHandler())
mux.HandleFunc("DELETE /extract", ss.deleteHandler())
h = ss.feedHandler()
mux.HandleFunc("GET /feed", h)
mux.HandleFunc("POST /feed", h)
mux.Handle("GET /.well-known/", healthchecks.Handler("/.well-known", db))
Expand Down
18 changes: 10 additions & 8 deletions internal/server/routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ func TestWellknown(t *testing.T) {
//ctx, cancel := context.WithCancel(context.Background())
//defer cancel()

mux, err := InitMux(&scrapeServer{}, nil)
mux, err := InitMux(&scrapeServer{}, nil, false)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -61,7 +61,7 @@ func TestExtractErrors(t *testing.T) {
WithURLFetcher(trafilatura.MustNew(nil)),
)

mux, err := InitMux(ss, nil)
mux, err := InitMux(ss, nil, false)
if err != nil {
t.Fatal(err)
}
Expand Down Expand Up @@ -105,12 +105,14 @@ func TestHomeHandlerAuth(t *testing.T) {
WithURLFetcher(&mockUrlFetcher{}),
WithAuthorizationIf(test.key),
)
req := httptest.NewRequest("GET", "http://foo.bar/", nil)
w := httptest.NewRecorder()
homeHandler(ss)(w, req)
resp := w.Result()
if resp.StatusCode != test.expectedResult {
t.Errorf("[%s] Expected %d, got %d", test.name, test.expectedResult, resp.StatusCode)
for _, openHome := range []bool{true, false} {
req := httptest.NewRequest("GET", "http://foo.bar/", nil)
w := httptest.NewRecorder()
homeHandler(ss, openHome)(w, req)
resp := w.Result()
if resp.StatusCode != test.expectedResult {
t.Errorf("[%s] Expected %d, got %d", test.name, test.expectedResult, resp.StatusCode)
}
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion internal/server/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func TestBatchReponseIsValid(t *testing.T) {
WithURLFetcher(fetcher),
)

mux, err := InitMux(ss, nil)
mux, err := InitMux(ss, nil, false)
if err != nil {
t.Fatal(err)
}
Expand Down
4 changes: 3 additions & 1 deletion internal/server/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@
}
</style>
</head>

<body>
<div class="page-container">
<div class="controls-container">
Expand All @@ -167,7 +168,7 @@
</div>
</form>
</div><!-- controls-container -->
<!-- {{if AuthEnabled}} -->
<!-- {{if ShowTokenWidget}} -->
<div class="token-container" x-data="tokenHandler()">
<div class="token-header">
<!-- TODO: Convert <a> to button, link hover color/state of +/- and button -->
Expand Down Expand Up @@ -257,4 +258,5 @@
}
</script>
</body>

</html>