feat: add OAuth 2.0 authorization code model and migration

Add the OAuthCode model for storing short-lived authorization codes
with PKCE challenges. Codes are hashed (SHA-256) before storage and
are single-use with a 10-minute expiry. Add the database migration
and OAuth-specific error types.
This commit is contained in:
kolaente 2026-03-26 16:31:47 +01:00 committed by kolaente
parent 7a258f67c7
commit 71282dcffd
6 changed files with 335 additions and 0 deletions

View File

@ -0,0 +1,2 @@
[]

View File

@ -0,0 +1,53 @@
// 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 migration
import (
"time"
"src.techknowlogick.com/xormigrate"
"xorm.io/xorm"
)
type oauthCodes20260226172819 struct {
ID int64 `xorm:"autoincr not null unique pk"`
UserID int64 `xorm:"bigint not null"`
Code string `xorm:"varchar(128) not null unique index"`
ExpiresAt time.Time `xorm:"not null"`
ClientID string `xorm:"varchar(255) not null"`
RedirectURI string `xorm:"text not null"`
CodeChallenge string `xorm:"varchar(128) not null"`
CodeChallengeMethod string `xorm:"varchar(10) not null"`
Created time.Time `xorm:"created not null"`
}
func (oauthCodes20260226172819) TableName() string {
return "oauth_codes"
}
func init() {
migrations = append(migrations, &xormigrate.Migration{
ID: "20260226172819",
Description: "add oauth_codes table for OAuth 2.0 authorization codes",
Migrate: func(tx *xorm.Engine) error {
return tx.Sync(oauthCodes20260226172819{})
},
Rollback: func(tx *xorm.Engine) error {
return tx.DropTables(oauthCodes20260226172819{})
},
})
}

View File

@ -2184,3 +2184,182 @@ func (err *ErrSessionNotFound) HTTPError() web.HTTPError {
Message: "The session does not exist.",
}
}
// ====================
// OAuth Server Errors
// ====================
// ErrOAuthClientNotFound represents an error where the OAuth client ID is not recognized.
type ErrOAuthClientNotFound struct{}
// IsErrOAuthClientNotFound checks if an error is ErrOAuthClientNotFound.
func IsErrOAuthClientNotFound(err error) bool {
_, ok := err.(*ErrOAuthClientNotFound)
return ok
}
func (err *ErrOAuthClientNotFound) Error() string {
return "OAuth client not found"
}
// ErrCodeOAuthClientNotFound holds the unique world-error code of this error
const ErrCodeOAuthClientNotFound = 17001
// HTTPError holds the http error description
func (err *ErrOAuthClientNotFound) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthClientNotFound,
Message: "The OAuth client ID is not recognized.",
}
}
// ErrOAuthInvalidRedirectURI represents an error where the redirect URI is not allowed.
type ErrOAuthInvalidRedirectURI struct{}
// IsErrOAuthInvalidRedirectURI checks if an error is ErrOAuthInvalidRedirectURI.
func IsErrOAuthInvalidRedirectURI(err error) bool {
_, ok := err.(*ErrOAuthInvalidRedirectURI)
return ok
}
func (err *ErrOAuthInvalidRedirectURI) Error() string {
return "Invalid redirect URI"
}
// ErrCodeOAuthInvalidRedirectURI holds the unique world-error code of this error
const ErrCodeOAuthInvalidRedirectURI = 17002
// HTTPError holds the http error description
func (err *ErrOAuthInvalidRedirectURI) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthInvalidRedirectURI,
Message: "The redirect URI is not allowed for this client.",
}
}
// ErrOAuthMissingPKCE represents an error where PKCE parameters are missing or invalid.
type ErrOAuthMissingPKCE struct{}
// IsErrOAuthMissingPKCE checks if an error is ErrOAuthMissingPKCE.
func IsErrOAuthMissingPKCE(err error) bool {
_, ok := err.(*ErrOAuthMissingPKCE)
return ok
}
func (err *ErrOAuthMissingPKCE) Error() string {
return "PKCE is required"
}
// ErrCodeOAuthMissingPKCE holds the unique world-error code of this error
const ErrCodeOAuthMissingPKCE = 17003
// HTTPError holds the http error description
func (err *ErrOAuthMissingPKCE) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthMissingPKCE,
Message: "PKCE (code_challenge with S256 method) is required.",
}
}
// ErrOAuthCodeInvalid represents an error where the authorization code is invalid or already used.
type ErrOAuthCodeInvalid struct{}
// IsErrOAuthCodeInvalid checks if an error is ErrOAuthCodeInvalid.
func IsErrOAuthCodeInvalid(err error) bool {
_, ok := err.(*ErrOAuthCodeInvalid)
return ok
}
func (err *ErrOAuthCodeInvalid) Error() string {
return "Invalid authorization code"
}
// ErrCodeOAuthCodeInvalid holds the unique world-error code of this error
const ErrCodeOAuthCodeInvalid = 17004
// HTTPError holds the http error description
func (err *ErrOAuthCodeInvalid) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthCodeInvalid,
Message: "The authorization code is invalid or has already been used.",
}
}
// ErrOAuthCodeExpired represents an error where the authorization code has expired.
type ErrOAuthCodeExpired struct{}
// IsErrOAuthCodeExpired checks if an error is ErrOAuthCodeExpired.
func IsErrOAuthCodeExpired(err error) bool {
_, ok := err.(*ErrOAuthCodeExpired)
return ok
}
func (err *ErrOAuthCodeExpired) Error() string {
return "Authorization code expired"
}
// ErrCodeOAuthCodeExpired holds the unique world-error code of this error
const ErrCodeOAuthCodeExpired = 17005
// HTTPError holds the http error description
func (err *ErrOAuthCodeExpired) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthCodeExpired,
Message: "The authorization code has expired.",
}
}
// ErrOAuthPKCEVerifyFailed represents an error where the PKCE code_verifier does not match.
type ErrOAuthPKCEVerifyFailed struct{}
// IsErrOAuthPKCEVerifyFailed checks if an error is ErrOAuthPKCEVerifyFailed.
func IsErrOAuthPKCEVerifyFailed(err error) bool {
_, ok := err.(*ErrOAuthPKCEVerifyFailed)
return ok
}
func (err *ErrOAuthPKCEVerifyFailed) Error() string {
return "PKCE verification failed"
}
// ErrCodeOAuthPKCEVerifyFailed holds the unique world-error code of this error
const ErrCodeOAuthPKCEVerifyFailed = 17006
// HTTPError holds the http error description
func (err *ErrOAuthPKCEVerifyFailed) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthPKCEVerifyFailed,
Message: "The code_verifier does not match the code_challenge.",
}
}
// ErrOAuthInvalidGrantType represents an error where the grant_type is not supported.
type ErrOAuthInvalidGrantType struct{}
// IsErrOAuthInvalidGrantType checks if an error is ErrOAuthInvalidGrantType.
func IsErrOAuthInvalidGrantType(err error) bool {
_, ok := err.(*ErrOAuthInvalidGrantType)
return ok
}
func (err *ErrOAuthInvalidGrantType) Error() string {
return "Invalid grant type"
}
// ErrCodeOAuthInvalidGrantType holds the unique world-error code of this error
const ErrCodeOAuthInvalidGrantType = 17007
// HTTPError holds the http error description
func (err *ErrOAuthInvalidGrantType) HTTPError() web.HTTPError {
return web.HTTPError{
HTTPCode: http.StatusBadRequest,
Code: ErrCodeOAuthInvalidGrantType,
Message: "The grant_type is not supported. Use 'authorization_code' or 'refresh_token'.",
}
}

View File

@ -70,6 +70,7 @@ func GetTables() []interface{} {
&TaskBucket{},
&TaskUnreadStatus{},
&Session{},
&OAuthCode{},
}
}

99
pkg/models/oauth_codes.go Normal file
View File

@ -0,0 +1,99 @@
// 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 models
import (
"time"
"code.vikunja.io/api/pkg/utils"
"xorm.io/xorm"
)
// OAuthCode represents a short-lived OAuth 2.0 authorization code.
type OAuthCode struct {
ID int64 `xorm:"autoincr not null unique pk" json:"id"`
UserID int64 `xorm:"bigint not null" json:"-"`
Code string `xorm:"varchar(128) not null unique index" json:"-"`
ExpiresAt time.Time `xorm:"not null" json:"-"`
ClientID string `xorm:"varchar(255) not null" json:"-"`
RedirectURI string `xorm:"text not null" json:"-"`
CodeChallenge string `xorm:"varchar(128) not null" json:"-"`
CodeChallengeMethod string `xorm:"varchar(10) not null" json:"-"`
Created time.Time `xorm:"created not null" json:"created"`
}
func (*OAuthCode) TableName() string {
return "oauth_codes"
}
// CreateOAuthCode generates a cryptographically random authorization code,
// stores it, and returns the code string.
func CreateOAuthCode(s *xorm.Session, userID int64, clientID, redirectURI, codeChallenge, codeChallengeMethod string) (code string, err error) {
rawCode, err := utils.CryptoRandomString(64)
if err != nil {
return "", err
}
oauthCode := &OAuthCode{
UserID: userID,
Code: HashSessionToken(rawCode),
ExpiresAt: time.Now().Add(10 * time.Minute),
ClientID: clientID,
RedirectURI: redirectURI,
CodeChallenge: codeChallenge,
CodeChallengeMethod: codeChallengeMethod,
}
_, err = s.Insert(oauthCode)
if err != nil {
return "", err
}
return rawCode, nil
}
// GetAndDeleteOAuthCode looks up an authorization code and deletes it (single-use).
// Returns the code record or an error if not found or expired.
func GetAndDeleteOAuthCode(s *xorm.Session, code string) (*OAuthCode, error) {
oauthCode := &OAuthCode{}
has, err := s.Where("code = ?", HashSessionToken(code)).Get(oauthCode)
if err != nil {
return nil, err
}
if !has {
return nil, &ErrOAuthCodeInvalid{}
}
// Delete immediately (single-use).
// Check affected rows to prevent a race where two concurrent requests
// both read the same code before either deletes it.
affected, err := s.Where("id = ?", oauthCode.ID).Delete(&OAuthCode{})
if err != nil {
return nil, err
}
if affected == 0 {
return nil, &ErrOAuthCodeInvalid{}
}
// Check expiry after deletion to prevent reuse of expired codes
if time.Now().After(oauthCode.ExpiresAt) {
return nil, &ErrOAuthCodeExpired{}
}
return oauthCode, nil
}

View File

@ -77,6 +77,7 @@ func SetupTests() {
"sessions",
"webhooks",
"totp",
"oauth_codes",
)
if err != nil {
log.Fatal(err)