Skip to content
Open
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
58 changes: 58 additions & 0 deletions challenge-5/submissions/kushalShukla-web/solution-template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package main

import (
"fmt"
"net/http"
)

const validToken = "secret"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Move secret to environment variable.

Hardcoding the authentication token is a security risk. In production, secrets should be loaded from environment variables or a secure configuration service.

Apply this diff to use an environment variable:

-const validToken = "secret"
+import "os"
+
+var validToken = getValidToken()
+
+func getValidToken() string {
+	token := os.Getenv("AUTH_TOKEN")
+	if token == "" {
+		panic("AUTH_TOKEN environment variable not set")
+	}
+	return token
+}
🤖 Prompt for AI Agents
In challenge-5/submissions/kushalShukla-web/solution-template.go around line 8,
the auth token is hardcoded as const validToken = "secret"; replace this by
reading the secret from an environment variable (e.g., os.Getenv("VALID_TOKEN"))
instead of a compile-time constant, remove the hardcoded value, and ensure the
application fails fast or logs a clear error if the env var is empty (returning
a 5xx or refusing to start) so secrets are not stored in source code.


// AuthMiddleware checks the "X-Auth-Token" header.
// If it's "secret", call the next handler.
// Otherwise, respond with 401 Unauthorized.
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// TODO: Implement the logic:
// 1) Grab the "X-Auth-Token" header
// 2) Compare against validToken
// 3) If mismatch or missing, respond with 401
// 4) Otherwise pass to next handler
authToken, exist := r.Header["X-Auth-Token"]
if !exist || authToken[0] != validToken {
http.Error(w, "", http.StatusUnauthorized)
return
}
Comment on lines +20 to +24
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Use idiomatic header access and provide meaningful error message.

The current implementation has two issues:

  1. Direct map access (r.Header["X-Auth-Token"]) is less idiomatic than r.Header.Get("X-Auth-Token"), which handles missing headers gracefully.
  2. The empty error message in http.Error(w, "", http.StatusUnauthorized) provides no feedback to the client.

Apply this diff to improve the implementation:

-		authToken, exist := r.Header["X-Auth-Token"]
-		if !exist || authToken[0] != validToken {
-			http.Error(w, "", http.StatusUnauthorized)
+		authToken := r.Header.Get("X-Auth-Token")
+		if authToken != validToken {
+			http.Error(w, "Unauthorized", http.StatusUnauthorized)
 			return
 		}
 		next.ServeHTTP(w, r)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
authToken, exist := r.Header["X-Auth-Token"]
if !exist || authToken[0] != validToken {
http.Error(w, "", http.StatusUnauthorized)
return
}
authToken := r.Header.Get("X-Auth-Token")
if authToken != validToken {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
🤖 Prompt for AI Agents
In challenge-5/submissions/kushalShukla-web/solution-template.go around lines 20
to 24, replace the direct map access to X-Auth-Token with the idiomatic
r.Header.Get("X-Auth-Token") to safely read the header, then compare that value
to validToken; if it doesn’t match, call http.Error(w, "unauthorized: invalid or
missing auth token", http.StatusUnauthorized) (or a similarly clear message) and
return so the client receives a meaningful error response.

next.ServeHTTP(w, r)

})
}

// helloHandler returns "Hello!" on GET /hello
func helloHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello!")
}

// secureHandler returns "You are authorized!" on GET /secure
func secureHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "You are authorized!")
}

// SetupServer configures the HTTP routes with the authentication middleware.
func SetupServer() http.Handler {
mux := http.NewServeMux()

// Public route: /hello (no auth required)
mux.HandleFunc("/hello", helloHandler)

// Secure route: /secure
// Wrap with AuthMiddleware
secureRoute := http.HandlerFunc(secureHandler)
mux.Handle("/secure", AuthMiddleware(secureRoute))

return mux
}

func main() {
// Optional: you can run a real server for local testing
http.ListenAndServe(":8080", SetupServer())
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add error handling for server startup.

http.ListenAndServe returns an error that should be handled. Without checking it, server startup failures will be silent.

Apply this diff to handle the error:

+	"log"
+
 func main() {
 	// Optional: you can run a real server for local testing
-	http.ListenAndServe(":8080", SetupServer())
+	log.Println("Starting server on :8080")
+	if err := http.ListenAndServe(":8080", SetupServer()); err != nil {
+		log.Fatalf("Server failed to start: %v", err)
+	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
http.ListenAndServe(":8080", SetupServer())
package main
import (
"net/http"
"log"
)
func main() {
// Optional: you can run a real server for local testing
log.Println("Starting server on :8080")
if err := http.ListenAndServe(":8080", SetupServer()); err != nil {
log.Fatalf("Server failed to start: %v", err)
}
}
🤖 Prompt for AI Agents
In challenge-5/submissions/kushalShukla-web/solution-template.go around line 57,
http.ListenAndServe(":8080", SetupServer()) is called without handling its
returned error; change this to capture the returned error and handle it (for
example assign err := http.ListenAndServe(...); if err != nil {
log.Fatalf("server failed to start: %v", err) } or use log.Println and
os.Exit(1) as appropriate) so startup failures are logged and the process exits
on error.

}