-
Notifications
You must be signed in to change notification settings - Fork 138
internal/testing: fake auth server #296
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,165 @@ | ||
package testing | ||
|
||
import ( | ||
"crypto/sha256" | ||
"encoding/base64" | ||
"encoding/json" | ||
"fmt" | ||
"log" | ||
"net/http" | ||
"time" | ||
|
||
"github.com/golang-jwt/jwt/v5" | ||
) | ||
|
||
const ( | ||
authServerPort = ":8080" | ||
issuer = "http://localhost" + authServerPort | ||
tokenExpiry = time.Hour | ||
) | ||
|
||
var jwtSigningKey = []byte("fake-secret-key") | ||
|
||
type authCodeInfo struct { | ||
codeChallenge string | ||
redirectURI string | ||
} | ||
|
||
// FakeAuthServer is a fake OAuth2 authorization server. | ||
type FakeAuthServer struct { | ||
server *http.Server | ||
authCodes map[string]authCodeInfo | ||
} | ||
|
||
func NewFakeAuthServer() *FakeAuthServer { | ||
server := &FakeAuthServer{ | ||
authCodes: make(map[string]authCodeInfo), | ||
} | ||
mux := http.NewServeMux() | ||
mux.HandleFunc("/.well-known/oauth-authorization-server", server.handleMetadata) | ||
mux.HandleFunc("/authorize", server.handleAuthorize) | ||
mux.HandleFunc("/token", server.handleToken) | ||
server.server = &http.Server{ | ||
Addr: authServerPort, | ||
Handler: mux, | ||
} | ||
return server | ||
} | ||
|
||
func (s *FakeAuthServer) Start() { | ||
go func() { | ||
if err := s.server.ListenAndServe(); err != http.ErrServerClosed { | ||
log.Fatalf("ListenAndServe(): %v", err) | ||
} | ||
}() | ||
} | ||
|
||
func (s *FakeAuthServer) Stop() { | ||
if err := s.server.Close(); err != nil { | ||
log.Printf("Failed to stop server: %v", err) | ||
} | ||
} | ||
|
||
func (s *FakeAuthServer) handleMetadata(w http.ResponseWriter, r *http.Request) { | ||
metadata := map[string]any{ | ||
"issuer": issuer, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Instead of hardcoding http://localhost:8080 as the issuer, should this use r.URL to find either the name or the port? RFC 8414 says the issuer is present to prevent "mix-up" attacks, but that's probably not much of a concern for a test-only implementation. To be extra cautious, however, maybe this could set the issuer to There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. RFC 8414 requires most/all of the URLs here to have an "https" scheme. The test server uses HTTP. Not sure if this is going to be a problem in practice, but this might be something else using httptest would help with, since it handles setting up a test server with TLS support. |
||
"authorization_endpoint": issuer + "/authorize", | ||
"token_endpoint": issuer + "/token", | ||
"jwks_uri": issuer + "/.well-known/jwks.json", | ||
"scopes_supported": []string{"openid", "profile", "email"}, | ||
"response_types_supported": []string{"code"}, | ||
"grant_types_supported": []string{"authorization_code"}, | ||
"token_endpoint_auth_methods_supported": []string{"none"}, | ||
"code_challenge_methods_supported": []string{"S256"}, | ||
} | ||
w.Header().Set("Content-Type", "application/json") | ||
json.NewEncoder(w).Encode(metadata) | ||
} | ||
|
||
func (s *FakeAuthServer) handleAuthorize(w http.ResponseWriter, r *http.Request) { | ||
query := r.URL.Query() | ||
responseType := query.Get("response_type") | ||
redirectURI := query.Get("redirect_uri") | ||
codeChallenge := query.Get("code_challenge") | ||
codeChallengeMethod := query.Get("code_challenge_method") | ||
|
||
if responseType != "code" { | ||
http.Error(w, "unsupported_response_type", http.StatusBadRequest) | ||
return | ||
} | ||
if redirectURI == "" { | ||
http.Error(w, "invalid_request", http.StatusBadRequest) | ||
return | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I might be missing something, but I believe redirect_uri is an optional parameter and only needs to be provided if a client has registered more than one redirect URI. I'm going to guess that this fake auth server will only be used with clients that always provide a redirect_uri? |
||
if codeChallenge == "" || codeChallengeMethod != "S256" { | ||
http.Error(w, "invalid_request", http.StatusBadRequest) | ||
return | ||
} | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Should this check for the required client_id field? (It doesn't use it, but perhaps it would be useful to return an error to a client which fails to provide it?) |
||
|
||
authCode := "fake-auth-code-" + fmt.Sprintf("%d", time.Now().UnixNano()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Unlikely though it is for a collision to happen here, perhaps this should include a counter or random component? |
||
s.authCodes[authCode] = authCodeInfo{ | ||
codeChallenge: codeChallenge, | ||
redirectURI: redirectURI, | ||
} | ||
|
||
redirectURL := fmt.Sprintf("%s?code=%s&state=%s", redirectURI, authCode, query.Get("state")) | ||
http.Redirect(w, r, redirectURL, http.StatusFound) | ||
} | ||
|
||
func (s *FakeAuthServer) handleToken(w http.ResponseWriter, r *http.Request) { | ||
r.ParseForm() | ||
grantType := r.Form.Get("grant_type") | ||
code := r.Form.Get("code") | ||
redirectURI := r.Form.Get("redirect_uri") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. redirect_uri was removed in OAuth 2.1: If this needs to support OAuth 2.0 clients, I believe it should validate redirect_uri when present but not complain when it isn't present. I suspect there's more to be done to support OAuth 2.0, though--I haven't checked to see what else changes. If this is only supporting OAuth 2.1 (https://modelcontextprotocol.io/specification/draft/basic/authorization only mentions 2.1) then I think it can ignore redirect_uri. |
||
codeVerifier := r.Form.Get("code_verifier") | ||
|
||
if grantType != "authorization_code" { | ||
http.Error(w, "unsupported_grant_type", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
authCodeInfo, ok := s.authCodes[code] | ||
if !ok { | ||
http.Error(w, "invalid_grant", http.StatusBadRequest) | ||
return | ||
} | ||
delete(s.authCodes, code) | ||
|
||
if authCodeInfo.redirectURI != redirectURI { | ||
http.Error(w, "invalid_grant", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// PKCE verification | ||
hasher := sha256.New() | ||
hasher.Write([]byte(codeVerifier)) | ||
calculatedChallenge := base64.RawURLEncoding.EncodeToString(hasher.Sum(nil)) | ||
if calculatedChallenge != authCodeInfo.codeChallenge { | ||
http.Error(w, "invalid_grant", http.StatusBadRequest) | ||
return | ||
} | ||
|
||
// Issue JWT | ||
now := time.Now() | ||
claims := jwt.MapClaims{ | ||
"iss": issuer, | ||
"sub": "fake-user-id", | ||
"aud": "fake-client-id", | ||
"exp": now.Add(tokenExpiry).Unix(), | ||
"iat": now.Unix(), | ||
} | ||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) | ||
accessToken, err := token.SignedString(jwtSigningKey) | ||
if err != nil { | ||
http.Error(w, "server_error", http.StatusInternalServerError) | ||
return | ||
} | ||
|
||
tokenResponse := map[string]any{ | ||
"access_token": accessToken, | ||
"token_type": "Bearer", | ||
"expires_in": int(tokenExpiry.Seconds()), | ||
} | ||
w.Header().Set("Content-Type", "application/json") | ||
json.NewEncoder(w).Encode(tokenResponse) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Instead of a complete fake server, would it be simpler to have a this package provide a ServeMux? In the case where you want a server, you can use httptest:
This pushes the start-a-server logic off to httptest, which already handles it, and doesn't seem substantially less convenient to use in tests.