By Abhijith N M · Reviewed 24 October 2026 · Editorial standards
Input validation belongs at the trust boundary: decode strictly, check required fields, enforce length and range limits, and allowlist where possible. Inside the service, domain rules still apply — a handler may forget a check, but the aggregator must not accept an impossible status. Defense in depth means the edge rejects bad payloads early and the domain refuses invalid state regardless of the caller.
Authentication answers 'who is calling'; authorization answers 'may they do this to that resource'. Keep them separate. Relay's API key identifies a tenant; authorization checks that the requested service belongs to that tenant. Confusing the two is how cross-tenant data leaks happen: a valid key should not imply access to every row.
Compare API keys and tokens with crypto/subtle.ConstantTimeCompare so timing does not leak how much of a secret matched. Never log tokens or passwords, never put them in URLs (they land in proxy logs and browser history), and load them from environment variables or a secret manager at startup, not from source code. Hash secrets at rest with a slow password hash; if you only need equality, storing a salted hash is still better than plaintext.
package main
import (
"crypto/subtle"
"errors"
"fmt"
"strings"
)
var errUnauthorized = errors.New("unauthorized")
func authorize(header, want string) error {
if !strings.HasPrefix(header, "Bearer ") {
return errUnauthorized
}
got := strings.TrimPrefix(header, "Bearer ")
if subtle.ConstantTimeCompare([]byte(got), []byte(want)) != 1 {
return errUnauthorized
}
return nil
}
func validateEvent(service, level string, status int) error {
if !strings.HasPrefix(service, "svc-") || strings.ContainsAny(service, " \t\n") {
return fmt.Errorf("service %q is not allowed", service)
}
switch level {
case "debug", "info", "warn", "error":
default:
return fmt.Errorf("unknown level %q", level)
}
if status < 100 || status > 599 {
return fmt.Errorf("invalid status %d", status)
}
return nil
}
func loadAPIKey(getenv func(string) string) (string, error) {
key := getenv("RELAY_API_KEY")
if key == "" {
return "", errors.New("RELAY_API_KEY is required")
}
return key, nil
}
func main() {
fmt.Println("missing header:", authorize("", "secret"))
fmt.Println("wrong token:", authorize("Bearer nope", "secret"))
fmt.Println("valid:", authorize("Bearer secret", "secret"))
fmt.Println("bad service:", validateEvent("api; DROP TABLE", "info", 200))
fmt.Println("ok:", validateEvent("svc-api", "info", 200))
key, err := loadAPIKey(func(string) string { return "demo-key" })
fmt.Println("key loaded:", err == nil, "length:", len(key))
}| Threat | Control |
|---|---|
| Injection via query or body | Parameterized queries; strict decoding; allowlist validation |
| Broken auth | Authentication middleware before handlers; deny by default |
| Cross-tenant access | Authorization check on every resource lookup |
| Credential leaks | Secrets from env/secret manager; never log or URL-encode them |
| Timing attacks | subtle.ConstantTimeCompare for secrets |
| Oversized input | io.LimitReader and request size limits |
| Dependency vulnerabilities | Pinned modules, go vet, govulncheck in CI |
Key takeaways
Validate input at the trust boundary and enforce domain invariants again inside the domain.
Keep authentication (who) separate from authorization (what they may access).
Compare secrets in constant time and never log or URL-encode them.
Load secrets from the environment or a secret manager; fail fast at startup when missing.
Deny by default and return uniform auth error responses.
Written and edited by the nexGenCoders team. Spotted a mistake? Tell us and we will fix it.
Don't lose this lesson
Create a free account to save your progress, keep your streak, and work toward a shareable certificate.