Files
vikunja/pkg/modules/auth/oauth2server/authorize.go
T
a59dbc2842 docs: add swagger annotations for the OAuth 2.0 endpoints (#3837)
`POST /api/v1/oauth/authorize` and `POST /api/v1/oauth/token` are served
but missing from the generated OpenAPI docs: the handlers in
`pkg/modules/auth/oauth2server` carry no swagger annotations, so neither
path is in `swagger.json` — 126 paths, no `oauth` among them.

Found while building a third-party client. The API answers fine; the
docs say the endpoints don't exist, so a client that validates its calls
against them can't use OAuth at all.

Adds annotations for both handlers and regenerates `pkg/swagger`. No
behaviour change — comments only, plus generated output. `mage
generate:swagger-docs` produces 521 insertions and 0 deletions, so
nothing else in the spec moved.

Checked against a 2.5.0 instance: `OPTIONS` on both paths returns
`Allow: OPTIONS, POST`, and `POST /api/v1/oauth/token` with no grant
type returns code 17007 naming `authorization_code` and `refresh_token`.

One judgement call worth a look: I annotated the token endpoint `@Accept
json`, matching the comment on `TokenRequest` that v1 binds JSON and v2
takes the form-encoded body. In practice v1 binds a form body too —
`Content-Type: application/x-www-form-urlencoded` with `grant_type=nope`
returns the same 17007 — so if you'd rather document both, say the word
and I'll widen it.

The `/api/v2` routes are untouched — happy to cover those too if you'd
like them in.

AI-assisted: annotations drafted with Claude, reviewed and tested by me.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 18:05:20 +00:00

129 lines
4.3 KiB
Go

// Vikunja is a to-do list application to facilitate your life.
// Copyright 2018-present Vikunja and contributors. All rights reserved.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
package oauth2server
import (
"net/http"
"code.vikunja.io/api/pkg/db"
"code.vikunja.io/api/pkg/models"
"code.vikunja.io/api/pkg/user"
"github.com/labstack/echo/v5"
)
// AuthorizeRequest represents the body for the authorize endpoint.
type AuthorizeRequest struct {
ResponseType string `json:"response_type"`
ClientID string `json:"client_id"`
RedirectURI string `json:"redirect_uri"`
State string `json:"state"`
CodeChallenge string `json:"code_challenge"`
CodeChallengeMethod string `json:"code_challenge_method"`
}
// AuthorizeResponse is returned on successful authorization code creation.
type AuthorizeResponse struct {
Code string `json:"code"`
RedirectURI string `json:"redirect_uri"`
State string `json:"state"`
}
// HandleAuthorize handles POST /oauth/authorize.
// It validates the OAuth parameters, creates an authorization code, and
// returns it as JSON. Authentication is handled by the token middleware.
// @Summary OAuth 2.0 authorize endpoint
// @Description Creates an authorization code for an OAuth 2.0 client on behalf of the authenticated user. PKCE is required. API tokens cannot be used to authorize a client.
// @tags auth
// @Accept json
// @Produce json
// @Security JWTKeyAuth
// @Param request body AuthorizeRequest true "The authorization request"
// @Success 200 {object} AuthorizeResponse "The authorization code and the redirect URI to return it to."
// @Failure 400 {object} web.HTTPError "response_type is not 'code', the redirect URI is invalid, or the PKCE challenge is missing."
// @Failure 403 {object} models.Message "An API token was used to authorize an OAuth client."
// @Failure 500 {object} models.Message "Internal server error."
// @Router /oauth/authorize [post]
func HandleAuthorize(c *echo.Context) error {
if c.Get("api_token") != nil {
return echo.NewHTTPError(http.StatusForbidden, "API tokens cannot be used to authorize OAuth clients")
}
var req AuthorizeRequest
if err := c.Bind(&req); err != nil {
return echo.NewHTTPError(http.StatusBadRequest, "Invalid request body")
}
// Get the authenticated user from the middleware
u, err := user.GetCurrentUser(c)
if err != nil {
return err
}
resp, err := Authorize(&req, u.ID)
if err != nil {
return err
}
return c.JSON(http.StatusOK, resp)
}
// Authorize validates the OAuth authorization parameters for the given
// authenticated user and creates a single-use authorization code, independent
// of the HTTP layer. Callers own request binding and resolving the user.
func Authorize(req *AuthorizeRequest, userID int64) (*AuthorizeResponse, error) {
// Validate response_type
if req.ResponseType != "code" {
return nil, echo.NewHTTPError(http.StatusBadRequest, "response_type must be 'code'")
}
// Validate redirect_uri
if !ValidateRedirectURI(req.RedirectURI) {
return nil, &models.ErrOAuthInvalidRedirectURI{}
}
// Validate PKCE (required)
if req.CodeChallenge == "" || req.CodeChallengeMethod != "S256" {
return nil, &models.ErrOAuthMissingPKCE{}
}
s := db.NewSession()
defer s.Close()
fullUser, err := user.GetUserByID(s, userID)
if err != nil {
_ = s.Rollback()
return nil, err
}
code, err := models.CreateOAuthCode(s, fullUser.ID, req.ClientID, req.RedirectURI, req.CodeChallenge, req.CodeChallengeMethod)
if err != nil {
_ = s.Rollback()
return nil, err
}
if err := s.Commit(); err != nil {
return nil, err
}
return &AuthorizeResponse{
Code: code,
RedirectURI: req.RedirectURI,
State: req.State,
}, nil
}