-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
* Move JWT auth into middleware * add a healthcheck * cleanup lock file on restart
- Loading branch information
Showing
7 changed files
with
407 additions
and
313 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,25 +1,27 @@ | ||
module github.com/lehigh-university-libraries/rollout | ||
|
||
go 1.22.0 | ||
go 1.23.4 | ||
|
||
require ( | ||
github.com/golang-jwt/jwt/v5 v5.2.1 | ||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 | ||
github.com/lestrrat-go/jwx v1.2.30 | ||
github.com/gorilla/mux v1.8.1 | ||
github.com/lestrrat-go/jwx/v2 v2.1.3 | ||
github.com/stretchr/testify v1.10.0 | ||
) | ||
|
||
require ( | ||
github.com/davecgh/go-spew v1.1.1 // indirect | ||
github.com/decred/dcrd/dcrec/secp256k1/v4 v4.3.0 // indirect | ||
github.com/goccy/go-json v0.10.3 // indirect | ||
github.com/lestrrat-go/backoff/v2 v2.0.8 // indirect | ||
github.com/lestrrat-go/blackmagic v1.0.2 // indirect | ||
github.com/lestrrat-go/httpcc v1.0.1 // indirect | ||
github.com/lestrrat-go/httprc v1.0.6 // indirect | ||
github.com/lestrrat-go/iter v1.0.2 // indirect | ||
github.com/lestrrat-go/option v1.0.1 // indirect | ||
github.com/pkg/errors v0.9.1 // indirect | ||
github.com/pmezard/go-difflib v1.0.0 // indirect | ||
github.com/segmentio/asm v1.2.0 // indirect | ||
golang.org/x/crypto v0.31.0 // indirect | ||
golang.org/x/sys v0.28.0 // indirect | ||
gopkg.in/yaml.v3 v3.0.1 // indirect | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,169 @@ | ||
package handler | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"fmt" | ||
"log/slog" | ||
"net/http" | ||
"os" | ||
"strings" | ||
"time" | ||
|
||
"github.com/lestrrat-go/jwx/v2/jwk" | ||
"github.com/lestrrat-go/jwx/v2/jwt" | ||
) | ||
|
||
type RolloutPayload struct { | ||
DockerImage string `json:"docker-image" env:"DOCKER_IMAGE"` | ||
DockerTag string `json:"docker-tag" env:"DOCKER_TAG"` | ||
GitRepo string `json:"git-repo" env:"GIT_REPO"` | ||
GitBranch string `json:"git-branch" env:"GIT_BRANCH"` | ||
Arg1 string `json:"rollout-arg1" env:"ROLLOUT_ARG1"` | ||
Arg2 string `json:"rollout-arg2" env:"ROLLOUT_ARG2"` | ||
Arg3 string `json:"rollout-arg3" env:"ROLLOUT_ARG3"` | ||
} | ||
|
||
type Handler struct{} | ||
|
||
func NewHandler() *Handler { | ||
return &Handler{} | ||
} | ||
|
||
// LoggingMiddleware logs incoming HTTP requests | ||
func LoggingMiddleware(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
start := time.Now() | ||
statusWriter := &statusRecorder{ | ||
ResponseWriter: w, | ||
statusCode: http.StatusOK, | ||
} | ||
next.ServeHTTP(statusWriter, r) | ||
duration := time.Since(start) | ||
slog.Info("Incoming request", | ||
"method", r.Method, | ||
"path", r.URL.Path, | ||
"status", statusWriter.statusCode, | ||
"duration", duration, | ||
"client_ip", r.RemoteAddr, | ||
"user_agent", r.UserAgent(), | ||
) | ||
}) | ||
} | ||
|
||
type statusRecorder struct { | ||
http.ResponseWriter | ||
statusCode int | ||
} | ||
|
||
func (rec *statusRecorder) WriteHeader(code int) { | ||
rec.statusCode = code | ||
rec.ResponseWriter.WriteHeader(code) | ||
} | ||
|
||
func HealthCheck(w http.ResponseWriter, r *http.Request) { | ||
_, err := w.Write([]byte("ok")) | ||
if err != nil { | ||
w.WriteHeader(http.StatusInternalServerError) | ||
slog.Error("Unable to write for healthcheck", "err", err) | ||
} | ||
} | ||
|
||
// JWTAuthMiddleware validates a JWT token and adds claims to the context | ||
func JWTAuthMiddleware(next http.Handler) http.Handler { | ||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
a := r.Header.Get("Authorization") | ||
if a == "" || !strings.HasPrefix(strings.ToLower(a), "bearer ") { | ||
http.Error(w, "Missing Authorization header", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
tokenString := a[7:] | ||
err := verifyJWT(tokenString) | ||
if err != nil { | ||
slog.Error("JWT verification failed", "err", err) | ||
http.Error(w, "Unauthorized", http.StatusUnauthorized) | ||
return | ||
} | ||
|
||
next.ServeHTTP(w, r) | ||
}) | ||
} | ||
|
||
func verifyJWT(tokenString string) error { | ||
keySet, err := fetchJWKS() | ||
if err != nil { | ||
return fmt.Errorf("unable to fetch JWKS: %v", err) | ||
} | ||
|
||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
|
||
token, err := jwt.Parse([]byte(tokenString), | ||
jwt.WithKeySet(keySet), | ||
jwt.WithVerify(true), | ||
jwt.WithContext(ctx), | ||
) | ||
if err != nil { | ||
return fmt.Errorf("unable to parse token: %v", err) | ||
} | ||
|
||
if err := validateClaims(token); err != nil { | ||
return fmt.Errorf("unable to validate claims: %v", err) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// validateClaims checks if the claims match the expected values | ||
func validateClaims(token jwt.Token) error { | ||
ccStr := os.Getenv("CUSTOM_CLAIMS") | ||
expectedClaims := make(map[string]string) | ||
if ccStr != "" { | ||
err := json.Unmarshal([]byte(ccStr), &expectedClaims) | ||
if err != nil { | ||
return fmt.Errorf("error decoding custom claims: %v", err) | ||
} | ||
} | ||
expectedClaims["aud"] = os.Getenv("JWT_AUD") | ||
|
||
for key, expectedValue := range expectedClaims { | ||
value, ok := token.Get(key) | ||
if !ok { | ||
return fmt.Errorf("missing claim: %s", key) | ||
} | ||
|
||
switch v := value.(type) { | ||
case string: | ||
if !strings.EqualFold(v, expectedValue) { | ||
return fmt.Errorf("invalid value for claim %s: %s", key, v) | ||
} | ||
case []string: | ||
if !strInSlice(expectedValue, v) { | ||
return fmt.Errorf("invalid value for claim %s: %s", key, v) | ||
} | ||
default: | ||
return fmt.Errorf("unsupported claim type for %s: %T", key, value) | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// fetchJWKS fetches the JSON Web Key Set (JWKS) from the given URI | ||
func fetchJWKS() (jwk.Set, error) { | ||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) | ||
defer cancel() | ||
|
||
jwksURI := os.Getenv("JWKS_URI") | ||
return jwk.Fetch(ctx, jwksURI) | ||
} | ||
|
||
func strInSlice(e string, s []string) bool { | ||
for _, a := range s { | ||
if a == e { | ||
return true | ||
} | ||
} | ||
return false | ||
} |
Oops, something went wrong.