|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "encoding/hex" |
| 7 | + "fmt" |
| 8 | + "log" |
| 9 | + "net/http" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/gin-gonic/gin" |
| 13 | + "github.com/gotify/server/v2/auth" |
| 14 | + "github.com/gotify/server/v2/config" |
| 15 | + "github.com/gotify/server/v2/database" |
| 16 | + "github.com/gotify/server/v2/model" |
| 17 | + "github.com/zitadel/oidc/v3/pkg/client/rp" |
| 18 | + httphelper "github.com/zitadel/oidc/v3/pkg/http" |
| 19 | + "github.com/zitadel/oidc/v3/pkg/oidc" |
| 20 | +) |
| 21 | + |
| 22 | +func NewOIDC(conf *config.Configuration, db *database.GormDatabase, userChangeNotifier *UserChangeNotifier) *OIDCAPI { |
| 23 | + scopes := conf.OIDC.Scopes |
| 24 | + if len(scopes) == 0 { |
| 25 | + scopes = []string{"openid", "profile", "email"} |
| 26 | + } |
| 27 | + |
| 28 | + cookieKey := make([]byte, 32) |
| 29 | + if _, err := rand.Read(cookieKey); err != nil { |
| 30 | + log.Fatalf("failed to generate OIDC cookie key: %v", err) |
| 31 | + } |
| 32 | + cookieHandlerOpt := []httphelper.CookieHandlerOpt{} |
| 33 | + if !conf.Server.SecureCookie { |
| 34 | + cookieHandlerOpt = append(cookieHandlerOpt, httphelper.WithUnsecure()) |
| 35 | + } |
| 36 | + cookieHandler := httphelper.NewCookieHandler(cookieKey, cookieKey, cookieHandlerOpt...) |
| 37 | + |
| 38 | + opts := []rp.Option{rp.WithCookieHandler(cookieHandler)} |
| 39 | + if conf.OIDC.Pkce { |
| 40 | + opts = append(opts, rp.WithPKCE(cookieHandler)) |
| 41 | + } |
| 42 | + |
| 43 | + provider, err := rp.NewRelyingPartyOIDC( |
| 44 | + context.Background(), |
| 45 | + conf.OIDC.Issuer, |
| 46 | + conf.OIDC.ClientID, |
| 47 | + conf.OIDC.ClientSecret, |
| 48 | + conf.OIDC.RedirectURL, |
| 49 | + scopes, |
| 50 | + opts..., |
| 51 | + ) |
| 52 | + if err != nil { |
| 53 | + log.Fatalf("failed to initialize OIDC provider: %v", err) |
| 54 | + } |
| 55 | + |
| 56 | + return &OIDCAPI{ |
| 57 | + DB: db, |
| 58 | + Provider: provider, |
| 59 | + UserChangeNotifier: userChangeNotifier, |
| 60 | + UsernameClaim: conf.OIDC.UsernameClaim, |
| 61 | + PasswordStrength: conf.PassStrength, |
| 62 | + SecureCookie: conf.Server.SecureCookie, |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +// OIDCAPI provides handlers for OIDC authentication. |
| 67 | +type OIDCAPI struct { |
| 68 | + DB *database.GormDatabase |
| 69 | + Provider rp.RelyingParty |
| 70 | + UserChangeNotifier *UserChangeNotifier |
| 71 | + UsernameClaim string |
| 72 | + PasswordStrength int |
| 73 | + SecureCookie bool |
| 74 | +} |
| 75 | + |
| 76 | +// LoginHandler redirects the user to the OIDC provider's authorization endpoint. |
| 77 | +func (a *OIDCAPI) LoginHandler() gin.HandlerFunc { |
| 78 | + return gin.WrapF(func(w http.ResponseWriter, r *http.Request) { |
| 79 | + clientName := r.URL.Query().Get("name") |
| 80 | + if clientName == "" { |
| 81 | + http.Error(w, "invalid client name", http.StatusBadRequest) |
| 82 | + return |
| 83 | + } |
| 84 | + nonce := make([]byte, 20) |
| 85 | + if _, err := rand.Read(nonce); err != nil { |
| 86 | + http.Error(w, "failed to generate state nonce", http.StatusInternalServerError) |
| 87 | + return |
| 88 | + } |
| 89 | + state := clientName + ":" + hex.EncodeToString(nonce) |
| 90 | + stateFunc := func() string { return state } |
| 91 | + rp.AuthURLHandler(stateFunc, a.Provider)(w, r) |
| 92 | + }) |
| 93 | +} |
| 94 | + |
| 95 | +// CallbackHandler handles the OIDC provider callback after authentication. |
| 96 | +func (a *OIDCAPI) CallbackHandler() gin.HandlerFunc { |
| 97 | + callback := func(w http.ResponseWriter, r *http.Request, tokens *oidc.Tokens[*oidc.IDTokenClaims], state string, provider rp.RelyingParty, info *oidc.UserInfo) { |
| 98 | + usernameRaw, ok := info.Claims[a.UsernameClaim] |
| 99 | + if !ok { |
| 100 | + http.Error(w, fmt.Sprintf("username claim %q is missing", a.UsernameClaim), http.StatusInternalServerError) |
| 101 | + return |
| 102 | + } |
| 103 | + |
| 104 | + username := fmt.Sprint(usernameRaw) |
| 105 | + if username == "" || usernameRaw == nil { |
| 106 | + http.Error(w, "Username claim was empty", http.StatusInternalServerError) |
| 107 | + return |
| 108 | + } |
| 109 | + |
| 110 | + user, err := a.DB.GetUserByName(username) |
| 111 | + if err != nil { |
| 112 | + http.Error(w, "database error", http.StatusInternalServerError) |
| 113 | + return |
| 114 | + } |
| 115 | + |
| 116 | + if user == nil { |
| 117 | + user = &model.User{Name: username, Admin: false, Pass: nil} |
| 118 | + if err := a.DB.CreateUser(user); err != nil { |
| 119 | + http.Error(w, "failed to create user", http.StatusInternalServerError) |
| 120 | + return |
| 121 | + } |
| 122 | + if err := a.UserChangeNotifier.fireUserAdded(user.ID); err != nil { |
| 123 | + log.Println("Could not notify user change") |
| 124 | + // Don't abort here, it's likely some plugin misbehaving. |
| 125 | + } |
| 126 | + } |
| 127 | + |
| 128 | + token := auth.GenerateNotExistingToken(generateClientToken, func(token string) bool { |
| 129 | + client, _ := a.DB.GetClientByToken(token) |
| 130 | + return client != nil |
| 131 | + }) |
| 132 | + |
| 133 | + clientName, _, _ := strings.Cut(state, ":") |
| 134 | + client := &model.Client{ |
| 135 | + Name: clientName, |
| 136 | + Token: token, |
| 137 | + UserID: user.ID, |
| 138 | + } |
| 139 | + if err := a.DB.CreateClient(client); err != nil { |
| 140 | + http.Error(w, "failed to create client", http.StatusInternalServerError) |
| 141 | + return |
| 142 | + } |
| 143 | + |
| 144 | + auth.SetCookie(w, token, auth.CookieMaxAge, a.SecureCookie) |
| 145 | + http.Redirect(w, r, "/", http.StatusTemporaryRedirect) |
| 146 | + } |
| 147 | + |
| 148 | + return gin.WrapF(rp.CodeExchangeHandler(rp.UserinfoCallback(callback), a.Provider)) |
| 149 | +} |
0 commit comments