-
Notifications
You must be signed in to change notification settings - Fork 578
feat: add oauth2 client support #2098
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
944c7a2
feat: add oauth2 client support
cemalkilic 660b23e
fix: rm nonexist id check
cemalkilic 5bf089a
fix: update test
cemalkilic cdc4833
fix: address PR comments
cemalkilic 080b812
fix: update test for client_name length
cemalkilic e877dbc
fix: add namespace prefix to enum
cemalkilic 1bec822
Merge branch 'master' into cemal/oauth-provider-client
cemalkilic File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 hidden or 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 hidden or 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 hidden or 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,50 @@ | ||
| package oauthserver | ||
|
|
||
| import ( | ||
| "encoding/base64" | ||
| "errors" | ||
| "net/http" | ||
| "strings" | ||
| ) | ||
|
|
||
| // ExtractClientCredentials extracts OAuth client credentials from the request | ||
| // Supports both Basic auth header and form body parameters | ||
| func ExtractClientCredentials(r *http.Request) (clientID, clientSecret string, err error) { | ||
| // First, try Basic auth header: Authorization: Basic base64(client_id:client_secret) | ||
| authHeader := r.Header.Get("Authorization") | ||
| if authHeader != "" && strings.HasPrefix(authHeader, "Basic ") { | ||
| encoded := strings.TrimPrefix(authHeader, "Basic ") | ||
| decoded, err := base64.StdEncoding.DecodeString(encoded) | ||
| if err != nil { | ||
| return "", "", errors.New("invalid basic auth encoding") | ||
| } | ||
|
|
||
| credentials := string(decoded) | ||
| parts := strings.SplitN(credentials, ":", 2) | ||
| if len(parts) != 2 { | ||
| return "", "", errors.New("invalid basic auth format") | ||
| } | ||
|
|
||
| return parts[0], parts[1], nil | ||
| } | ||
|
|
||
| // Fall back to form parameters | ||
| if err := r.ParseForm(); err != nil { | ||
| return "", "", errors.New("failed to parse form") | ||
| } | ||
|
|
||
| clientID = r.FormValue("client_id") | ||
| clientSecret = r.FormValue("client_secret") | ||
|
|
||
| // Return empty credentials if both are empty (no client auth attempted) | ||
| if clientID == "" && clientSecret == "" { | ||
| return "", "", nil | ||
| } | ||
|
|
||
| // If only one is provided, it's an error | ||
| if clientID == "" || clientSecret == "" { | ||
| return "", "", errors.New("both client_id and client_secret must be provided") | ||
| } | ||
|
|
||
| return clientID, clientSecret, nil | ||
| } |
This file contains hidden or 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,184 @@ | ||
| package oauthserver | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "net/http" | ||
| "time" | ||
|
|
||
| "github.com/go-chi/chi/v5" | ||
| "github.com/supabase/auth/internal/api/apierrors" | ||
| "github.com/supabase/auth/internal/api/shared" | ||
| "github.com/supabase/auth/internal/models" | ||
| "github.com/supabase/auth/internal/observability" | ||
| ) | ||
|
|
||
| // OAuthServerClientResponse represents the response format for OAuth client operations | ||
| type OAuthServerClientResponse struct { | ||
| ClientID string `json:"client_id"` | ||
| ClientSecret string `json:"client_secret,omitempty"` // only returned on registration | ||
|
|
||
| RedirectURIs []string `json:"redirect_uris"` | ||
| TokenEndpointAuthMethod []string `json:"token_endpoint_auth_method"` | ||
| GrantTypes []string `json:"grant_types"` | ||
| ResponseTypes []string `json:"response_types"` | ||
| ClientName string `json:"client_name,omitempty"` | ||
| ClientURI string `json:"client_uri,omitempty"` | ||
| LogoURI string `json:"logo_uri,omitempty"` | ||
|
|
||
| // Metadata fields | ||
| RegistrationType string `json:"registration_type"` | ||
| CreatedAt time.Time `json:"created_at"` | ||
| UpdatedAt time.Time `json:"updated_at"` | ||
| } | ||
|
|
||
| // OAuthServerClientListResponse represents the response for listing OAuth clients | ||
| type OAuthServerClientListResponse struct { | ||
| Clients []OAuthServerClientResponse `json:"clients"` | ||
| } | ||
|
|
||
| // oauthServerClientToResponse converts a model to response format | ||
| func oauthServerClientToResponse(client *models.OAuthServerClient, includeSecret bool) *OAuthServerClientResponse { | ||
| response := &OAuthServerClientResponse{ | ||
| ClientID: client.ClientID, | ||
|
|
||
| // OAuth 2.1 DCR fields | ||
| RedirectURIs: client.GetRedirectURIs(), | ||
| TokenEndpointAuthMethod: []string{"client_secret_basic", "client_secret_post"}, // Both methods are supported | ||
| GrantTypes: client.GetGrantTypes(), | ||
| ResponseTypes: []string{"code"}, // Always "code" in OAuth 2.1 | ||
| ClientName: client.ClientName.String(), | ||
| ClientURI: client.ClientURI.String(), | ||
| LogoURI: client.LogoURI.String(), | ||
|
|
||
| // Metadata fields | ||
| RegistrationType: client.RegistrationType, | ||
| CreatedAt: client.CreatedAt, | ||
| UpdatedAt: client.UpdatedAt, | ||
| } | ||
|
|
||
| // Only include client_secret during registration | ||
| if includeSecret { | ||
| // Note: This will be filled in by the handler with the plaintext secret | ||
| response.ClientSecret = "" | ||
| } | ||
|
|
||
| return response | ||
| } | ||
|
|
||
| // LoadOAuthServerClient is middleware that loads an OAuth server client from the URL parameter | ||
| func (s *Server) LoadOAuthServerClient(w http.ResponseWriter, r *http.Request) (context.Context, error) { | ||
| ctx := r.Context() | ||
| clientID := chi.URLParam(r, "client_id") | ||
|
|
||
| if clientID == "" { | ||
| return nil, apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, "client_id is required") | ||
| } | ||
|
|
||
| observability.LogEntrySetField(r, "oauth_client_id", clientID) | ||
|
|
||
| client, err := s.getOAuthServerClient(ctx, clientID) | ||
| if err != nil { | ||
| if models.IsNotFoundError(err) { | ||
| return nil, apierrors.NewNotFoundError(apierrors.ErrorCodeUserNotFound, "OAuth client not found") | ||
| } | ||
| return nil, apierrors.NewInternalServerError("Error loading OAuth client").WithInternalError(err) | ||
| } | ||
|
|
||
| ctx = WithOAuthServerClient(ctx, client) | ||
| return ctx, nil | ||
| } | ||
|
|
||
| // AdminOAuthServerClientRegister handles POST /admin/oauth/clients (manual registration by admins) | ||
| func (s *Server) AdminOAuthServerClientRegister(w http.ResponseWriter, r *http.Request) error { | ||
| ctx := r.Context() | ||
|
|
||
| var params OAuthServerClientRegisterParams | ||
| if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { | ||
| return apierrors.NewBadRequestError(apierrors.ErrorCodeBadJSON, "Invalid JSON body") | ||
| } | ||
|
|
||
| // Force registration type to manual for admin endpoint | ||
| params.RegistrationType = "manual" | ||
|
|
||
| client, plaintextSecret, err := s.registerOAuthServerClient(ctx, ¶ms) | ||
| if err != nil { | ||
| return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, err.Error()) | ||
| } | ||
|
|
||
| response := oauthServerClientToResponse(client, true) | ||
| response.ClientSecret = plaintextSecret | ||
|
|
||
| return shared.SendJSON(w, http.StatusCreated, response) | ||
| } | ||
|
|
||
| // OAuthServerClientDynamicRegister handles POST /oauth/register (OAuth 2.1 Dynamic Client Registration) | ||
| func (s *Server) OAuthServerClientDynamicRegister(w http.ResponseWriter, r *http.Request) error { | ||
| ctx := r.Context() | ||
|
|
||
| // Check if dynamic registration is enabled | ||
| if !s.config.OAuthServer.AllowDynamicRegistration { | ||
| return apierrors.NewForbiddenError(apierrors.ErrorCodeOAuthDynamicClientRegistrationDisabled, "Dynamic client registration is not enabled") | ||
| } | ||
|
|
||
| var params OAuthServerClientRegisterParams | ||
| if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil { | ||
| return apierrors.NewBadRequestError(apierrors.ErrorCodeBadJSON, "Invalid JSON body") | ||
| } | ||
|
|
||
| params.RegistrationType = "dynamic" | ||
|
|
||
| client, plaintextSecret, err := s.registerOAuthServerClient(ctx, ¶ms) | ||
| if err != nil { | ||
| return apierrors.NewBadRequestError(apierrors.ErrorCodeValidationFailed, err.Error()) | ||
| } | ||
|
|
||
| response := oauthServerClientToResponse(client, true) | ||
| response.ClientSecret = plaintextSecret | ||
|
|
||
| return shared.SendJSON(w, http.StatusCreated, response) | ||
| } | ||
|
|
||
| // OAuthServerClientGet handles GET /admin/oauth/clients/{client_id} | ||
| func (s *Server) OAuthServerClientGet(w http.ResponseWriter, r *http.Request) error { | ||
| ctx := r.Context() | ||
| client := GetOAuthServerClient(ctx) | ||
|
|
||
| response := oauthServerClientToResponse(client, false) | ||
| return shared.SendJSON(w, http.StatusOK, response) | ||
| } | ||
|
|
||
| // OAuthServerClientDelete handles DELETE /admin/oauth/clients/{client_id} | ||
| func (s *Server) OAuthServerClientDelete(w http.ResponseWriter, r *http.Request) error { | ||
| ctx := r.Context() | ||
| client := GetOAuthServerClient(ctx) | ||
|
|
||
| if err := s.deleteOAuthServerClient(ctx, client.ClientID); err != nil { | ||
| return apierrors.NewInternalServerError("Error deleting OAuth client").WithInternalError(err) | ||
| } | ||
|
|
||
| w.WriteHeader(http.StatusNoContent) | ||
| return nil | ||
| } | ||
|
|
||
| // OAuthServerClientList handles GET /admin/oauth/clients | ||
| func (s *Server) OAuthServerClientList(w http.ResponseWriter, r *http.Request) error { | ||
| ctx := r.Context() | ||
| db := s.db.WithContext(ctx) | ||
|
|
||
| var clients []models.OAuthServerClient | ||
| if err := db.Q().Where("deleted_at is null").Order("created_at desc").All(&clients); err != nil { | ||
| return apierrors.NewInternalServerError("Error listing OAuth clients").WithInternalError(err) | ||
| } | ||
|
|
||
| responses := make([]OAuthServerClientResponse, len(clients)) | ||
| for i, client := range clients { | ||
| responses[i] = *oauthServerClientToResponse(&client, false) | ||
| } | ||
|
|
||
| response := OAuthServerClientListResponse{ | ||
| Clients: responses, | ||
| } | ||
|
|
||
| return shared.SendJSON(w, http.StatusOK, response) | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.