1
Fork 0
mirror of https://github.com/jech/galene.git synced 2024-11-23 00:55:58 +01:00
galene/webserver/api.go

644 lines
13 KiB
Go
Raw Normal View History

package webserver
import (
2024-04-09 16:53:03 +02:00
"crypto/rand"
"crypto/sha256"
2024-05-01 22:12:48 +02:00
"encoding/base64"
2024-04-09 16:53:03 +02:00
"encoding/hex"
"encoding/json"
"errors"
2024-04-09 16:53:03 +02:00
"io"
"mime"
"net/http"
2024-04-09 16:53:03 +02:00
"os"
"strings"
2024-04-09 16:53:03 +02:00
"golang.org/x/crypto/pbkdf2"
"github.com/jech/galene/group"
"github.com/jech/galene/stats"
2024-05-01 22:12:48 +02:00
"github.com/jech/galene/token"
)
2024-04-09 16:53:03 +02:00
// checkAdmin checks whether the client authentifies as an administrator
func checkAdmin(w http.ResponseWriter, r *http.Request) bool {
username, password, ok := r.BasicAuth()
2024-04-09 16:53:03 +02:00
if ok {
ok, _ = adminMatch(username, password)
}
if !ok {
2024-04-09 16:53:03 +02:00
failAuthentication(w, "/galene-api/")
return false
}
return true
}
// checkPasswordAdmin checks whether the client authentifies as either an
// administrator or the given user. It is used to check whether the
// client has the right to change user's password.
func checkPasswordAdmin(w http.ResponseWriter, r *http.Request, groupname, user string, wildcard bool) bool {
2024-04-09 16:53:03 +02:00
username, password, ok := r.BasicAuth()
if ok {
ok, _ := adminMatch(username, password)
if ok {
return true
}
}
if ok && !wildcard && username == user {
2024-04-09 16:53:03 +02:00
desc, err := group.GetDescription(groupname)
if err == nil && desc.Users != nil {
u, ok := desc.Users[user]
if ok {
ok, _ := u.Password.Match(password)
if ok {
return true
}
}
}
}
failAuthentication(w, "/galene-api/")
return false
}
2024-05-03 20:11:36 +02:00
func sendJSON(w http.ResponseWriter, r *http.Request, v any) {
w.Header().Set("content-type", "application/json")
if r.Method == "HEAD" {
return
}
e := json.NewEncoder(w)
e.Encode(v)
}
func getText(w http.ResponseWriter, r *http.Request) ([]byte, bool) {
ctype, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || !strings.EqualFold(ctype, "text/plain") {
w.Header().Set("Accept", "text/plain")
2024-05-03 20:11:36 +02:00
http.Error(w, "unsupported content type",
http.StatusUnsupportedMediaType)
return nil, true
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 4096))
if err != nil {
httpError(w, err)
return nil, true
}
return body, false
}
func getJSON(w http.ResponseWriter, r *http.Request, v any) bool {
ctype, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || !strings.EqualFold(ctype, "application/json") {
w.Header().Set("Accept", "application/json")
2024-05-03 20:11:36 +02:00
http.Error(w, "unsupported content type",
http.StatusUnsupportedMediaType)
return true
}
d := json.NewDecoder(r.Body)
err = d.Decode(v)
2024-05-03 20:11:36 +02:00
if err != nil {
httpError(w, err)
return true
}
return false
}
2024-04-09 16:53:03 +02:00
func apiHandler(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, "/galene-api/") {
http.NotFound(w, r)
return
}
first, kind, rest := splitPath(r.URL.Path[len("/galene-api"):])
2024-05-03 18:33:37 +02:00
if first == "/v0" && kind == ".stats" && rest == "" {
2024-04-09 16:53:03 +02:00
if !checkAdmin(w, r) {
return
}
if r.Method != "HEAD" && r.Method != "GET" {
methodNotAllowed(w, "HEAD", "GET")
return
}
w.Header().Set("cache-control", "no-cache")
2024-05-03 20:11:36 +02:00
sendJSON(w, r, stats.GetGroups())
2024-04-09 16:53:03 +02:00
return
2024-05-03 18:33:37 +02:00
} else if first == "/v0" && kind == ".groups" {
2024-04-09 16:53:03 +02:00
apiGroupHandler(w, r, rest)
return
}
2024-04-09 16:53:03 +02:00
http.NotFound(w, r)
return
}
func apiGroupHandler(w http.ResponseWriter, r *http.Request, pth string) {
first, kind, rest := splitPath(pth)
if first == "" {
notFound(w)
return
}
g := first[1:]
if g == "" && kind == "" {
if !checkAdmin(w, r) {
return
}
if r.Method != "HEAD" && r.Method != "GET" {
methodNotAllowed(w, "HEAD", "GET")
return
}
groups, err := group.GetDescriptionNames()
if err != nil {
2024-04-09 16:53:03 +02:00
httpError(w, err)
return
}
2024-05-03 20:11:36 +02:00
sendJSON(w, r, groups)
return
}
2024-04-09 16:53:03 +02:00
if kind == ".users" {
2024-04-14 01:04:44 +02:00
usersHandler(w, r, g, rest)
2024-04-09 16:53:03 +02:00
return
} else if kind == ".empty-user" {
specialUserHandler(w, r, g, rest, false)
return
} else if kind == ".wildcard-user" {
specialUserHandler(w, r, g, rest, true)
return
2024-04-11 13:25:59 +02:00
} else if kind == ".keys" && rest == "" {
keysHandler(w, r, g)
return
2024-05-01 22:12:48 +02:00
} else if kind == ".tokens" {
tokensHandler(w, r, g, rest)
return
2024-04-09 16:53:03 +02:00
} else if kind != "" {
if !checkAdmin(w, r) {
return
}
notFound(w)
return
}
2024-04-09 16:53:03 +02:00
if !checkAdmin(w, r) {
return
}
2024-04-09 16:53:03 +02:00
if r.Method == "HEAD" || r.Method == "GET" {
desc, etag, err := group.GetSanitisedDescription(g)
if err != nil {
httpError(w, err)
return
}
w.Header().Set("etag", etag)
done := checkPreconditions(w, r, etag)
if done {
return
}
2024-05-03 20:11:36 +02:00
sendJSON(w, r, desc)
2024-04-09 16:53:03 +02:00
return
} else if r.Method == "PUT" {
etag, err := group.GetDescriptionTag(g)
if errors.Is(err, os.ErrNotExist) {
2024-04-09 16:53:03 +02:00
err = nil
etag = ""
} else if err != nil {
httpError(w, err)
return
}
done := checkPreconditions(w, r, etag)
if done {
return
}
var newdesc group.Description
2024-05-03 20:11:36 +02:00
done = getJSON(w, r, &newdesc)
if done {
2024-04-09 16:53:03 +02:00
return
}
err = group.UpdateDescription(g, etag, &newdesc)
if err != nil {
httpError(w, err)
return
}
if etag == "" {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusNoContent)
}
return
} else if r.Method == "DELETE" {
etag, err := group.GetDescriptionTag(g)
if err != nil {
httpError(w, err)
return
}
done := checkPreconditions(w, r, etag)
if done {
return
}
err = group.DeleteDescription(g, etag)
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
methodNotAllowed(w, "HEAD", "GET", "PUT", "DELETE")
return
}
2024-04-14 01:04:44 +02:00
func usersHandler(w http.ResponseWriter, r *http.Request, g, pth string) {
2024-05-01 22:20:02 +02:00
if pth == "" {
http.NotFound(w, r)
return
}
2024-04-09 16:53:03 +02:00
if pth == "/" {
if !checkAdmin(w, r) {
return
}
if r.Method != "HEAD" && r.Method != "GET" {
2024-05-03 20:30:46 +02:00
methodNotAllowed(w, "HEAD", "GET")
2024-04-09 16:53:03 +02:00
return
}
users, etag, err := group.GetUsers(g)
if err != nil {
httpError(w, err)
return
}
w.Header().Set("etag", etag)
done := checkPreconditions(w, r, etag)
if done {
return
}
2024-05-03 20:11:36 +02:00
sendJSON(w, r, users)
2024-04-09 16:53:03 +02:00
return
}
2024-04-09 16:53:03 +02:00
first2, kind2, rest2 := splitPath(pth)
2024-05-03 20:36:51 +02:00
if first2 != "" && kind2 == "" {
userHandler(w, r, g, first2[1:], false)
2024-05-03 20:36:51 +02:00
return
} else if first2 != "" && kind2 == ".password" && rest2 == "" {
passwordHandler(w, r, g, first2[1:], false)
return
}
if !checkAdmin(w, r) {
return
}
notFound(w)
return
}
func specialUserHandler(w http.ResponseWriter, r *http.Request, g, pth string, wildcard bool) {
if pth == "" {
userHandler(w, r, g, "", wildcard)
return
} else if pth == "/.password" {
passwordHandler(w, r, g, "", wildcard)
2024-04-09 16:53:03 +02:00
return
2024-05-03 20:36:51 +02:00
}
if !checkAdmin(w, r) {
2024-04-09 16:53:03 +02:00
return
}
2024-05-03 20:36:51 +02:00
notFound(w)
return
}
2024-04-09 16:53:03 +02:00
func userHandler(w http.ResponseWriter, r *http.Request, g, user string, wildcard bool) {
2024-04-09 16:53:03 +02:00
if !checkAdmin(w, r) {
return
}
if r.Method == "HEAD" || r.Method == "GET" {
user, etag, err := group.GetSanitisedUser(g, user, wildcard)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
w.Header().Set("etag", etag)
done := checkPreconditions(w, r, etag)
if done {
return
}
2024-05-03 20:11:36 +02:00
sendJSON(w, r, user)
2024-04-09 16:53:03 +02:00
return
} else if r.Method == "PUT" {
etag, err := group.GetUserTag(g, user, wildcard)
if errors.Is(err, os.ErrNotExist) {
2024-04-09 16:53:03 +02:00
etag = ""
err = nil
} else if err != nil {
httpError(w, err)
return
}
done := checkPreconditions(w, r, etag)
if done {
return
}
var newdesc group.UserDescription
2024-05-03 20:11:36 +02:00
done = getJSON(w, r, &newdesc)
if done {
2024-04-09 16:53:03 +02:00
return
}
err = group.UpdateUser(g, user, wildcard, etag, &newdesc)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
if etag == "" {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusNoContent)
}
return
} else if r.Method == "DELETE" {
etag, err := group.GetUserTag(g, user, wildcard)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
done := checkPreconditions(w, r, etag)
if done {
return
}
err = group.DeleteUser(g, user, wildcard, etag)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
2024-04-09 16:53:03 +02:00
methodNotAllowed(w, "HEAD", "GET", "PUT", "DELETE")
return
}
func passwordHandler(w http.ResponseWriter, r *http.Request, g, user string, wildcard bool) {
if !checkPasswordAdmin(w, r, g, user, wildcard) {
2024-04-09 16:53:03 +02:00
return
}
if r.Method == "PUT" {
var pw group.Password
2024-05-03 20:11:36 +02:00
done := getJSON(w, r, &pw)
if done {
2024-04-09 16:53:03 +02:00
return
}
err := group.SetUserPassword(g, user, wildcard, pw)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
} else if r.Method == "POST" {
2024-05-03 20:11:36 +02:00
body, done := getText(w, r)
if done {
2024-04-09 16:53:03 +02:00
return
}
salt := make([]byte, 8)
2024-05-03 20:11:36 +02:00
_, err := rand.Read(salt)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
iterations := 4096
key := pbkdf2.Key(body, salt, iterations, 32, sha256.New)
encoded := hex.EncodeToString(key)
2024-04-09 16:53:03 +02:00
pw := group.Password{
Type: "pbkdf2",
Hash: "sha-256",
Key: &encoded,
2024-04-09 16:53:03 +02:00
Salt: hex.EncodeToString(salt),
Iterations: iterations,
}
err = group.SetUserPassword(g, user, wildcard, pw)
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
} else if r.Method == "DELETE" {
err := group.SetUserPassword(g, user, wildcard, group.Password{})
2024-04-09 16:53:03 +02:00
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
methodNotAllowed(w, "PUT", "POST", "DELETE")
return
}
2024-04-11 13:25:59 +02:00
type jwkset = struct {
Keys []map[string]any `json:"keys"`
}
func keysHandler(w http.ResponseWriter, r *http.Request, g string) {
if !checkAdmin(w, r) {
return
}
if r.Method == "PUT" {
2024-05-03 20:11:36 +02:00
// cannot use getJSON due to the weird content-type
ctype, _, err :=
mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil ||
!strings.EqualFold(ctype, "application/jwk-set+json") {
w.Header().Set("Accept", "application/jwk-set+json")
2024-04-11 13:25:59 +02:00
http.Error(w, "unsupported content type",
http.StatusUnsupportedMediaType)
return
}
d := json.NewDecoder(r.Body)
var keys jwkset
err = d.Decode(&keys)
2024-04-11 13:25:59 +02:00
if err != nil {
httpError(w, err)
return
}
err = group.SetKeys(g, keys.Keys)
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
} else if r.Method == "DELETE" {
err := group.SetKeys(g, nil)
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
methodNotAllowed(w, "PUT", "DELETE")
return
}
2024-05-01 22:12:48 +02:00
func tokensHandler(w http.ResponseWriter, r *http.Request, g, pth string) {
if pth == "" {
http.NotFound(w, r)
return
}
if !checkAdmin(w, r) {
return
}
if pth == "/" {
if r.Method == "HEAD" || r.Method == "GET" {
tokens, etag, err := token.List(g)
if err != nil {
httpError(w, err)
return
}
w.Header().Set("content-type", "application/json")
2024-05-01 22:12:48 +02:00
if etag != "" {
w.Header().Set("etag", etag)
}
toknames := make([]string, len(tokens))
for i, t := range tokens {
toknames[i] = t.Token
2024-05-01 22:12:48 +02:00
}
2024-05-03 20:11:36 +02:00
sendJSON(w, r, toknames)
2024-05-01 22:12:48 +02:00
return
} else if r.Method == "POST" {
var newtoken token.Stateful
2024-05-03 20:11:36 +02:00
done := getJSON(w, r, &newtoken)
if done {
2024-05-01 22:12:48 +02:00
return
}
if newtoken.Token != "" || newtoken.Group != "" {
http.Error(w, "overspecified token",
http.StatusBadRequest)
return
}
buf := make([]byte, 8)
rand.Read(buf)
newtoken.Token =
base64.RawURLEncoding.EncodeToString(buf)
newtoken.Group = g
t, err := token.Update(&newtoken, "")
if err != nil {
httpError(w, err)
return
}
w.Header().Set("location", t.Token)
w.WriteHeader(http.StatusCreated)
return
}
methodNotAllowed(w, "HEAD", "GET", "POST")
return
}
if pth[0] != '/' {
http.NotFound(w, r)
return
}
t := pth[1:]
if r.Method == "HEAD" || r.Method == "GET" {
old, etag, err := token.Get(t)
2024-05-01 22:12:48 +02:00
if err != nil {
httpError(w, err)
return
}
if old.Group != g {
2024-05-01 22:12:48 +02:00
http.NotFound(w, r)
return
}
tok := old.Clone()
tok.Token = ""
tok.Group = ""
2024-05-01 22:12:48 +02:00
w.Header().Set("etag", etag)
done := checkPreconditions(w, r, etag)
if done {
return
}
sendJSON(w, r, tok)
2024-05-01 22:12:48 +02:00
return
} else if r.Method == "PUT" {
old, etag, err := token.Get(t)
if errors.Is(err, os.ErrNotExist) {
etag = ""
err = nil
} else if err != nil {
httpError(w, err)
return
}
if old.Group != g {
http.Error(w, "token exists in different group",
http.StatusConflict)
return
}
done := checkPreconditions(w, r, etag)
if done {
return
}
var newtoken token.Stateful
2024-05-03 20:11:36 +02:00
done = getJSON(w, r, &newtoken)
if done {
2024-05-01 22:12:48 +02:00
return
}
if newtoken.Group != "" || newtoken.Token != "" {
http.Error(w, "overspecified token",
http.StatusBadRequest)
2024-05-02 18:14:51 +02:00
return
}
newtoken.Group = g
newtoken.Token = t
2024-05-01 22:12:48 +02:00
_, err = token.Update(&newtoken, etag)
if err != nil {
httpError(w, err)
return
}
if etag == "" {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusNoContent)
}
return
} else if r.Method == "DELETE" {
old, etag, err := token.Get(t)
if err != nil {
httpError(w, err)
return
}
if old.Group != g {
http.NotFound(w, r)
return
}
done := checkPreconditions(w, r, etag)
if done {
return
}
err = token.Delete(t, etag)
if err != nil {
httpError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
return
}
methodNotAllowed(w, "HEAD", "GET", "PUT", "DELETE")
return
}