| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "net/http" |
| 6 | "strings" |
| 7 | "time" |
| 8 | |
| 9 | "gitlab.com/Timfa/bluegit/internal/access" |
| 10 | "golang.org/x/crypto/ssh" |
| 11 | ) |
| 12 | |
| 13 | func (s *Server) login(w http.ResponseWriter, r *http.Request) { |
| 14 | if s.who(r).OK { |
| 15 | http.Redirect(w, r, "/", http.StatusFound) |
| 16 | return |
| 17 | } |
| 18 | if s.Dev { |
| 19 | id, err := s.Auth.Exchange(r.Context(), "dev", s.Cfg.RedirectURI()) |
| 20 | if err != nil { |
| 21 | http.Error(w, err.Error(), http.StatusBadGateway) |
| 22 | return |
| 23 | } |
| 24 | s.finishLogin(w, r, id.AuthID, id.Username, id.AvatarURL, id.IsAdmin, id.AccessToken, id.ExpiresIn) |
| 25 | return |
| 26 | } |
| 27 | state, err := randomState() |
| 28 | if err != nil { |
| 29 | http.Error(w, "sessie", http.StatusInternalServerError) |
| 30 | return |
| 31 | } |
| 32 | secure := strings.HasPrefix(s.Cfg.BaseURL, "https://") |
| 33 | http.SetCookie(w, &http.Cookie{ |
| 34 | Name: "bluegit_oauth_state", Value: state, Path: "/", MaxAge: 600, |
| 35 | HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode, |
| 36 | }) |
| 37 | http.Redirect(w, r, s.Auth.AuthorizeURL(state, s.Cfg.RedirectURI()), http.StatusFound) |
| 38 | } |
| 39 | |
| 40 | func (s *Server) callback(w http.ResponseWriter, r *http.Request) { |
| 41 | if s.Dev { |
| 42 | http.NotFound(w, r) |
| 43 | return |
| 44 | } |
| 45 | if msg := r.URL.Query().Get("error"); msg != "" { |
| 46 | s.redirect(w, r, "/login", "", "Aanmelden mislukt: "+msg) |
| 47 | return |
| 48 | } |
| 49 | stateCookie, err := r.Cookie("bluegit_oauth_state") |
| 50 | if err != nil || stateCookie.Value == "" || stateCookie.Value != r.URL.Query().Get("state") { |
| 51 | http.Error(w, "ongeldige aanmeldstatus", http.StatusBadRequest) |
| 52 | return |
| 53 | } |
| 54 | http.SetCookie(w, &http.Cookie{Name: "bluegit_oauth_state", Value: "", Path: "/", MaxAge: -1}) |
| 55 | id, err := s.Auth.Exchange(r.Context(), r.URL.Query().Get("code"), s.Cfg.RedirectURI()) |
| 56 | if err != nil { |
| 57 | s.Log.Error("oauth", "err", err) |
| 58 | s.redirect(w, r, "/", "", "Aanmelden bij auth.timfalken.com is mislukt") |
| 59 | return |
| 60 | } |
| 61 | s.finishLogin(w, r, id.AuthID, id.Username, id.AvatarURL, id.IsAdmin, id.AccessToken, id.ExpiresIn) |
| 62 | } |
| 63 | |
| 64 | func (s *Server) finishLogin(w http.ResponseWriter, r *http.Request, authID int64, username, avatar string, authAdmin bool, token string, expiresIn int) { |
| 65 | if expiresIn <= 0 { |
| 66 | expiresIn = 86400 |
| 67 | } |
| 68 | user, err := s.Store.UpsertUser(r.Context(), authID, username, avatar, authAdmin) |
| 69 | if err != nil { |
| 70 | http.Error(w, err.Error(), http.StatusBadRequest) |
| 71 | return |
| 72 | } |
| 73 | exp := time.Now().Add(time.Duration(expiresIn) * time.Second) |
| 74 | sess, err := s.Store.CreateSession(r.Context(), user.ID, token, exp) |
| 75 | if err != nil { |
| 76 | http.Error(w, "sessie", http.StatusInternalServerError) |
| 77 | return |
| 78 | } |
| 79 | s.setSessionCookie(w, sess.ID, exp) |
| 80 | s.redirect(w, r, "/", "Welkom, "+user.Username, "") |
| 81 | } |
| 82 | |
| 83 | func (s *Server) logout(w http.ResponseWriter, r *http.Request) { |
| 84 | if !s.csrfOK(w, r) { |
| 85 | return |
| 86 | } |
| 87 | p := s.who(r) |
| 88 | if p.OK { |
| 89 | _ = s.Auth.Logout(r.Context(), p.Session.AccessToken) |
| 90 | _ = s.Store.DeleteSession(r.Context(), p.Session.ID) |
| 91 | } |
| 92 | http.SetCookie(w, &http.Cookie{Name: "bluegit_session", Value: "", Path: "/", MaxAge: -1}) |
| 93 | http.Redirect(w, r, "/", http.StatusSeeOther) |
| 94 | } |
| 95 | |
| 96 | func (s *Server) home(w http.ResponseWriter, r *http.Request) { |
| 97 | v := s.view(w, r, "BlueGit") |
| 98 | if v.User != nil { |
| 99 | ids, err := s.Store.ListRepoIDs(r.Context(), v.User.ID, v.User.InstanceAdmin) |
| 100 | if err != nil { |
| 101 | http.Error(w, "overzicht", http.StatusInternalServerError) |
| 102 | return |
| 103 | } |
| 104 | repos, err := s.Store.ReposByIDs(r.Context(), ids) |
| 105 | if err != nil { |
| 106 | http.Error(w, "overzicht", http.StatusInternalServerError) |
| 107 | return |
| 108 | } |
| 109 | v.Repos = repos |
| 110 | groups, err := s.Store.ListGroups(r.Context(), v.User.ID, v.User.InstanceAdmin) |
| 111 | if err != nil { |
| 112 | http.Error(w, "overzicht", http.StatusInternalServerError) |
| 113 | return |
| 114 | } |
| 115 | v.Groups = groups |
| 116 | s.render(w, "dashboard", v) |
| 117 | return |
| 118 | } |
| 119 | ids, err := s.Store.ListRepoIDs(r.Context(), 0, false) |
| 120 | if err == nil { |
| 121 | v.Repos, _ = s.Store.ReposByIDs(r.Context(), ids) |
| 122 | } |
| 123 | s.render(w, "home", v) |
| 124 | } |
| 125 | |
| 126 | func (s *Server) newPage(w http.ResponseWriter, r *http.Request) { |
| 127 | if _, ok := s.loginRequired(w, r); !ok { |
| 128 | return |
| 129 | } |
| 130 | v := s.view(w, r, "Nieuw") |
| 131 | v.Groups, _ = s.Store.ListGroups(r.Context(), v.User.ID, false) |
| 132 | s.render(w, "new", v) |
| 133 | } |
| 134 | |
| 135 | func (s *Server) account(w http.ResponseWriter, r *http.Request) { |
| 136 | u, ok := s.loginRequired(w, r) |
| 137 | if !ok { |
| 138 | return |
| 139 | } |
| 140 | v := s.view(w, r, "Account") |
| 141 | v.Tokens, _ = s.Store.ListTokens(r.Context(), u.ID) |
| 142 | v.Keys, _ = s.Store.ListSSHKeys(r.Context(), u.ID) |
| 143 | v.NewToken = cookieVal(r, "bluegit_token_once") |
| 144 | if v.NewToken != "" { |
| 145 | http.SetCookie(w, &http.Cookie{Name: "bluegit_token_once", Value: "", Path: "/", MaxAge: -1}) |
| 146 | } |
| 147 | s.render(w, "account", v) |
| 148 | } |
| 149 | |
| 150 | func (s *Server) createToken(w http.ResponseWriter, r *http.Request) { |
| 151 | u, ok := s.loginRequired(w, r) |
| 152 | if !ok || !s.csrfOK(w, r) { |
| 153 | return |
| 154 | } |
| 155 | plain, err := s.Store.CreateToken(r.Context(), u.ID, r.FormValue("name")) |
| 156 | if err != nil { |
| 157 | s.redirect(w, r, "/settings", "", err.Error()) |
| 158 | return |
| 159 | } |
| 160 | secure := strings.HasPrefix(s.Cfg.BaseURL, "https://") |
| 161 | http.SetCookie(w, &http.Cookie{Name: "bluegit_token_once", Value: plain, Path: "/settings", MaxAge: 120, HttpOnly: true, Secure: secure, SameSite: http.SameSiteLaxMode}) |
| 162 | s.redirect(w, r, "/settings", "Token aangemaakt. Kopieer hem nu; hij wordt niet opnieuw getoond.", "") |
| 163 | } |
| 164 | |
| 165 | func (s *Server) deleteToken(w http.ResponseWriter, r *http.Request) { |
| 166 | u, ok := s.loginRequired(w, r) |
| 167 | if !ok || !s.csrfOK(w, r) { |
| 168 | return |
| 169 | } |
| 170 | var id int64 |
| 171 | _, _ = parseID(r.FormValue("id"), &id) |
| 172 | if err := s.Store.DeleteToken(r.Context(), u.ID, id); err != nil { |
| 173 | s.redirect(w, r, "/settings", "", "token niet gevonden") |
| 174 | return |
| 175 | } |
| 176 | s.redirect(w, r, "/settings", "Token ingetrokken", "") |
| 177 | } |
| 178 | |
| 179 | func (s *Server) addSSH(w http.ResponseWriter, r *http.Request) { |
| 180 | u, ok := s.loginRequired(w, r) |
| 181 | if !ok || !s.csrfOK(w, r) { |
| 182 | return |
| 183 | } |
| 184 | line := strings.TrimSpace(r.FormValue("key")) |
| 185 | pub, _, _, _, err := ssh.ParseAuthorizedKey([]byte(line)) |
| 186 | if err != nil { |
| 187 | s.redirect(w, r, "/settings", "", "dat is geen OpenSSH-publieke sleutel") |
| 188 | return |
| 189 | } |
| 190 | stored := strings.TrimSpace(string(ssh.MarshalAuthorizedKey(pub))) |
| 191 | fp := ssh.FingerprintSHA256(pub) |
| 192 | if err := s.Store.AddSSHKey(r.Context(), u.ID, r.FormValue("name"), stored, fp); err != nil { |
| 193 | s.redirect(w, r, "/settings", "", err.Error()) |
| 194 | return |
| 195 | } |
| 196 | s.redirect(w, r, "/settings", "Sleutel toegevoegd", "") |
| 197 | } |
| 198 | |
| 199 | func (s *Server) deleteSSH(w http.ResponseWriter, r *http.Request) { |
| 200 | u, ok := s.loginRequired(w, r) |
| 201 | if !ok || !s.csrfOK(w, r) { |
| 202 | return |
| 203 | } |
| 204 | var id int64 |
| 205 | _, _ = parseID(r.FormValue("id"), &id) |
| 206 | if err := s.Store.DeleteSSHKey(r.Context(), u.ID, id); err != nil { |
| 207 | s.redirect(w, r, "/settings", "", "sleutel niet gevonden") |
| 208 | return |
| 209 | } |
| 210 | s.redirect(w, r, "/settings", "Sleutel verwijderd", "") |
| 211 | } |
| 212 | |
| 213 | func (s *Server) export(w http.ResponseWriter, r *http.Request) { |
| 214 | u, ok := s.loginRequired(w, r) |
| 215 | if !ok { |
| 216 | return |
| 217 | } |
| 218 | type secretRow struct { |
| 219 | Scope string `json:"scope"` |
| 220 | Name string `json:"name"` |
| 221 | Value string `json:"value"` |
| 222 | } |
| 223 | var secrets []secretRow |
| 224 | ids, _ := s.Store.ListRepoIDs(r.Context(), u.ID, false) |
| 225 | for _, id := range ids { |
| 226 | role, err := s.Store.EffectiveRole(r.Context(), u.ID, id) |
| 227 | if err != nil || !role.CanManageSecrets() { |
| 228 | continue |
| 229 | } |
| 230 | repo, err := s.Store.RepoByID(r.Context(), id) |
| 231 | if err != nil { |
| 232 | continue |
| 233 | } |
| 234 | vals, err := s.Store.SecretValues(r.Context(), "repo", id, true) |
| 235 | if err != nil { |
| 236 | continue |
| 237 | } |
| 238 | for name, value := range vals { |
| 239 | secrets = append(secrets, secretRow{Scope: "repo:" + repo.FullPath(), Name: name, Value: value}) |
| 240 | } |
| 241 | } |
| 242 | groups, _ := s.Store.ListGroups(r.Context(), u.ID, false) |
| 243 | for _, g := range groups { |
| 244 | role, err := s.Store.GroupRole(r.Context(), g.ID, u.ID) |
| 245 | if err != nil || !role.AtLeast(access.RoleMaintainer) { |
| 246 | continue |
| 247 | } |
| 248 | vals, err := s.Store.SecretValues(r.Context(), "group", g.ID, true) |
| 249 | if err != nil { |
| 250 | continue |
| 251 | } |
| 252 | for name, value := range vals { |
| 253 | secrets = append(secrets, secretRow{Scope: "group:" + g.Path, Name: name, Value: value}) |
| 254 | } |
| 255 | } |
| 256 | tokens, _ := s.Store.ListTokens(r.Context(), u.ID) |
| 257 | keys, _ := s.Store.ListSSHKeys(r.Context(), u.ID) |
| 258 | payload := map[string]any{ |
| 259 | "exported_at": time.Now().UTC().Format(time.RFC3339), |
| 260 | "account": map[string]any{ |
| 261 | "id": u.AuthID, |
| 262 | "username": u.Username, |
| 263 | "avatar_url": u.AvatarURL, |
| 264 | "instance_admin": u.InstanceAdmin, |
| 265 | }, |
| 266 | "tokens": tokens, |
| 267 | "ssh_keys": keys, |
| 268 | "secrets": secrets, |
| 269 | } |
| 270 | w.Header().Set("Content-Type", "application/json; charset=utf-8") |
| 271 | w.Header().Set("Content-Disposition", `attachment; filename="bluegit-export.json"`) |
| 272 | enc := json.NewEncoder(w) |
| 273 | enc.SetIndent("", " ") |
| 274 | _ = enc.Encode(payload) |
| 275 | } |
| 276 | |
| 277 | func parseID(s string, dest *int64) (int64, error) { |
| 278 | var n int64 |
| 279 | for _, c := range s { |
| 280 | if c < '0' || c > '9' { |
| 281 | return 0, errBadID |
| 282 | } |
| 283 | n = n*10 + int64(c-'0') |
| 284 | } |
| 285 | if dest != nil { |
| 286 | *dest = n |
| 287 | } |
| 288 | return n, nil |
| 289 | } |
| 290 | |
| 291 | var errBadID = http.ErrMissingFile |