Skip to content
Merged
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,6 @@ mock-oauth2-server

# env file
.env

# Server binary
server
11 changes: 7 additions & 4 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ func main() {

// Determine the base URL for OpenID Connect configuration
baseURL := host

// If host flag is not provided, check for IssuerURL in config (from MOCK_ISSUER_URL env var)
if baseURL == "" {
baseURL = cfg.IssuerURL
}

// If neither host flag nor MOCK_ISSUER_URL env var is provided, use localhost
if baseURL == "" {
baseURL = fmt.Sprintf("http://localhost:%d", serverPort)
Expand All @@ -70,14 +70,17 @@ func main() {

// Set up routes
mux.Handle("/authorize", &handlers.AuthorizeHandler{Store: memoryStore})
mux.Handle("/token", handlers.NewTokenHandler(memoryStore))
mux.Handle("/token", handlers.NewTokenHandlerWithIssuer(memoryStore, baseURL))
mux.Handle("/userinfo", &handlers.UserInfoHandler{Store: memoryStore})
mux.Handle("/config", handlers.NewConfigHandler(memoryStore, defaultUser))
mux.Handle("/version", handlers.NewVersionHandler())

// Add OpenID Connect Discovery endpoint
mux.Handle("/.well-known/openid-configuration", handlers.NewOpenIDConfigHandler(baseURL))

// Add JWKS endpoint
mux.Handle("/jwks", handlers.NewJWKSHandler())

// Start the server with the custom ServeMux
startServer(serverPort, mux)
}
Expand Down
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ require (
github.com/google/uuid v1.6.0
golang.org/x/oauth2 v0.28.0
)

require github.com/golang-jwt/jwt/v5 v5.3.0 // indirect
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/golang-jwt/jwt/v5 v5.3.0 h1:pv4AsKCKKZuqlgs5sUmn4x8UlGa0kEVt/puTpKx9vvo=
github.com/golang-jwt/jwt/v5 v5.3.0/go.mod h1:fxCRLWMO43lRc8nhHWY6LGqRcf+1gQWArsqaEUEa5bE=
github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
Expand Down
4 changes: 2 additions & 2 deletions internal/config/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,10 @@ func TestGetConfig(t *testing.T) {
if retrievedConfig.Port != 8082 ||
retrievedConfig.MockUserEmail != "getconfig@example.com" ||
retrievedConfig.MockUserName != "GetConfig User" ||
retrievedConfig.MockTokenExpiry != 1800 ||
retrievedConfig.MockTokenExpiry != 1800 ||
retrievedConfig.IssuerURL != "http://getconfig-mock-oauth2:8082" {

t.Errorf("expected retrievedConfig to match updated config, got Port: %d, MockUserEmail: %s, MockUserName: %s, MockTokenExpiry: %d, IssuerURL: %s",
t.Errorf("expected retrievedConfig to match updated config, got Port: %d, MockUserEmail: %s, MockUserName: %s, MockTokenExpiry: %d, IssuerURL: %s",
retrievedConfig.Port, retrievedConfig.MockUserEmail, retrievedConfig.MockUserName, retrievedConfig.MockTokenExpiry, retrievedConfig.IssuerURL)
}
}
31 changes: 31 additions & 0 deletions internal/handlers/jwks.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package handlers

import (
"encoding/json"
"net/http"

"github.com/chrisw-dev/golang-mock-oauth2-server/internal/jwt"
)

// JWKSHandler handles requests for JSON Web Key Set
type JWKSHandler struct{}

// NewJWKSHandler creates a new JWKS handler
func NewJWKSHandler() *JWKSHandler {
return &JWKSHandler{}
}

// ServeHTTP handles HTTP requests for JWKS
func (h *JWKSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
jwks, err := jwt.GetJWKS()
if err != nil {
http.Error(w, "Error generating JWKS", http.StatusInternalServerError)
return
}

w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(jwks); err != nil {
http.Error(w, "Error encoding JWKS", http.StatusInternalServerError)
return
}
}
72 changes: 72 additions & 0 deletions internal/handlers/jwks_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package handlers

import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)

func TestJWKSHandler(t *testing.T) {
handler := NewJWKSHandler()

req := httptest.NewRequest("GET", "/jwks", nil)
rr := httptest.NewRecorder()

handler.ServeHTTP(rr, req)

if rr.Code != http.StatusOK {
t.Errorf("Expected status code %d, got %d", http.StatusOK, rr.Code)
}

// Check content type
contentType := rr.Header().Get("Content-Type")
if contentType != "application/json" {
t.Errorf("Expected content type application/json, got %s", contentType)
}

// Parse the response
var jwks map[string]interface{}
err := json.NewDecoder(rr.Body).Decode(&jwks)
if err != nil {
t.Fatalf("Failed to decode JWKS response: %v", err)
}

// Verify JWKS structure
keys, ok := jwks["keys"].([]interface{})
if !ok {
t.Fatal("JWKS should have a 'keys' array")
}

if len(keys) == 0 {
t.Error("JWKS keys array should not be empty")
}

// Check the first key
key, ok := keys[0].(map[string]interface{})
if !ok {
t.Fatal("Key should be a map")
}

requiredFields := []string{"kty", "use", "kid", "alg", "n", "e"}
for _, field := range requiredFields {
if _, exists := key[field]; !exists {
t.Errorf("Key should have field %s", field)
}
}

// Verify key type is RSA
if key["kty"] != "RSA" {
t.Errorf("Expected kty to be RSA, got %v", key["kty"])
}

// Verify algorithm is RS256
if key["alg"] != "RS256" {
t.Errorf("Expected alg to be RS256, got %v", key["alg"])
}

// Verify use is sig
if key["use"] != "sig" {
t.Errorf("Expected use to be sig, got %v", key["use"])
}
}
54 changes: 46 additions & 8 deletions internal/handlers/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,33 @@ import (
"encoding/json"
"log"
"net/http"
"strings"
"time"

"github.com/chrisw-dev/golang-mock-oauth2-server/internal/jwt"
"github.com/chrisw-dev/golang-mock-oauth2-server/internal/models"
"github.com/chrisw-dev/golang-mock-oauth2-server/internal/store"
)

// TokenHandler handles OAuth2 token exchange requests
type TokenHandler struct {
store store.Store
store store.Store
issuerURL string
}

// NewTokenHandler creates a new TokenHandler with the given store
func NewTokenHandler(store store.Store) *TokenHandler {
return &TokenHandler{
store: store,
store: store,
issuerURL: "http://localhost:8080", // default issuer
}
}

// NewTokenHandlerWithIssuer creates a new TokenHandler with the given store and issuer URL
func NewTokenHandlerWithIssuer(store store.Store, issuerURL string) *TokenHandler {
return &TokenHandler{
store: store,
issuerURL: issuerURL,
}
}

Expand Down Expand Up @@ -69,12 +81,26 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// Generate token response
accessToken, err := generateAccessToken(h.issuerURL, clientID, authRequest.Scope)
if err != nil {
log.Printf("Error generating access token: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

idToken, err := generateIDToken(h.issuerURL, clientID)
if err != nil {
log.Printf("Error generating ID token: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}

tokenResponse := models.TokenResponse{
AccessToken: generateAccessToken(clientID),
AccessToken: accessToken,
TokenType: "Bearer",
ExpiresIn: 3600,
RefreshToken: generateRefreshToken(clientID),
IDToken: generateIDToken(clientID),
IDToken: idToken,
}

// Store the token in the store for future validation
Expand All @@ -94,8 +120,17 @@ func (h *TokenHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}

// Helper function to generate a mock access token
func generateAccessToken(clientID string) string {
return "mock-access-token-" + clientID + "-" + time.Now().Format("20060102150405")
func generateAccessToken(issuerURL, clientID, scope string) (string, error) {
// Parse scopes from the scope string
scopes := strings.Fields(scope)
if len(scopes) == 0 {
scopes = []string{"openid"}
}

// Generate a subject ID based on client ID
sub := "user-" + clientID

return jwt.GenerateAccessToken(issuerURL, clientID, sub, scopes)
}

// Helper function to generate a mock refresh token
Expand All @@ -104,6 +139,9 @@ func generateRefreshToken(clientID string) string {
}

// Helper function to generate a mock ID token
func generateIDToken(clientID string) string {
return "mock-id-token-" + clientID + "-" + time.Now().Format("20060102150405")
func generateIDToken(issuerURL, clientID string) (string, error) {
// Generate a subject ID based on client ID
sub := "user-" + clientID

return jwt.GenerateIDToken(issuerURL, clientID, sub)
}
43 changes: 43 additions & 0 deletions internal/handlers/token_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import (
"strings"
"testing"

"github.com/chrisw-dev/golang-mock-oauth2-server/internal/jwt"
"github.com/chrisw-dev/golang-mock-oauth2-server/internal/models"
"github.com/chrisw-dev/golang-mock-oauth2-server/internal/store"
jwtlib "github.com/golang-jwt/jwt/v5"
)

func TestTokenHandler(t *testing.T) {
Expand Down Expand Up @@ -61,4 +63,45 @@ func TestTokenHandler(t *testing.T) {
if response.TokenType != "Bearer" {
t.Errorf("Expected token_type to be 'Bearer', got '%s'", response.TokenType)
}

// Verify that ID token is a valid JWT
if response.IDToken == "" {
t.Errorf("Expected ID token to be present")
}

// Parse ID token to verify it's a valid JWT
parser := jwtlib.NewParser()
idToken, _, err := parser.ParseUnverified(response.IDToken, jwtlib.MapClaims{})
if err != nil {
t.Errorf("Failed to parse ID token as JWT: %v", err)
}

// Check that the token has standard JWT headers
if _, ok := idToken.Header["alg"]; !ok {
t.Error("ID token should have 'alg' header")
}

if _, ok := idToken.Header["kid"]; !ok {
t.Error("ID token should have 'kid' header")
}

// Verify the ID token using our JWT package
claims, err := jwt.VerifyToken(response.IDToken)
if err != nil {
t.Errorf("Failed to verify ID token: %v", err)
}

if claims == nil {
t.Error("ID token claims should not be nil")
}

// Verify that access token is a valid JWT
accessToken, _, err := parser.ParseUnverified(response.AccessToken, jwtlib.MapClaims{})
if err != nil {
t.Errorf("Failed to parse access token as JWT: %v", err)
}

if _, ok := accessToken.Header["alg"]; !ok {
t.Error("Access token should have 'alg' header")
}
}
Loading