portal/api/s5/http.go

497 lines
11 KiB
Go
Raw Normal View History

2024-01-15 04:54:43 +00:00
package s5
import (
"bytes"
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
2024-01-16 07:01:18 +00:00
"encoding/hex"
2024-01-15 04:54:43 +00:00
"errors"
"git.lumeweb.com/LumeWeb/libs5-go/encoding"
2024-01-15 19:41:24 +00:00
"git.lumeweb.com/LumeWeb/libs5-go/types"
2024-01-16 07:01:18 +00:00
"git.lumeweb.com/LumeWeb/portal/db/models"
2024-01-15 04:54:43 +00:00
"git.lumeweb.com/LumeWeb/portal/interfaces"
emailverifier "github.com/AfterShip/email-verifier"
2024-01-15 04:54:43 +00:00
"go.sia.tech/jape"
"go.uber.org/zap"
"io"
"mime/multipart"
"net/http"
"strings"
"time"
2024-01-15 04:54:43 +00:00
)
const (
errMultiformParse = "Error parsing multipart form"
errRetrievingFile = "Error retrieving the file"
errReadFile = "Error reading the file"
errClosingStream = "Error closing the stream"
errUploadingFile = "Error uploading the file"
errAccountGenerateChallenge = "Error generating challenge"
errAccountRegister = "Error registering account"
2024-01-16 18:51:03 +00:00
errAccountLogin = "Error logging in account"
2024-01-15 04:54:43 +00:00
)
var (
errUploadingFileErr = errors.New(errUploadingFile)
errAccountGenerateChallengeErr = errors.New(errAccountGenerateChallenge)
errAccountRegisterErr = errors.New(errAccountRegister)
errInvalidChallengeErr = errors.New("Invalid challenge")
errInvalidSignatureErr = errors.New("Invalid signature")
errPubkeyNotSupported = errors.New("Only ed25519 keys are supported")
errInvalidEmail = errors.New("Invalid email")
errEmailAlreadyExists = errors.New("Email already exists")
errGeneratingPassword = errors.New("Error generating password")
errPubkeyAlreadyExists = errors.New("Pubkey already exists")
2024-01-16 18:51:03 +00:00
errAccountLoginErr = errors.New(errAccountLogin)
2024-01-15 04:54:43 +00:00
)
2024-01-16 16:42:50 +00:00
type HttpHandler struct {
portal interfaces.Portal
verifier *emailverifier.Verifier
2024-01-15 04:54:43 +00:00
}
2024-01-16 16:42:50 +00:00
func NewHttpHandler(portal interfaces.Portal) *HttpHandler {
verifier := emailverifier.NewVerifier()
verifier.DisableSMTPCheck()
verifier.DisableGravatarCheck()
verifier.DisableDomainSuggest()
verifier.DisableAutoUpdateDisposable()
return &HttpHandler{
portal: portal,
verifier: verifier,
}
2024-01-15 04:54:43 +00:00
}
2024-01-16 16:42:50 +00:00
func (h *HttpHandler) SmallFileUpload(jc jape.Context) {
2024-01-15 20:16:48 +00:00
var rs io.ReadSeeker
var bufferSize int64
2024-01-15 04:54:43 +00:00
r := jc.Request
contentType := r.Header.Get("Content-Type")
if strings.HasPrefix(contentType, "multipart/form-data") {
2024-01-15 04:54:43 +00:00
// Parse the multipart form
err := r.ParseMultipartForm(h.portal.Config().GetInt64("core.post-upload-limit"))
if jc.Check(errMultiformParse, err) != nil {
h.portal.Logger().Error(errMultiformParse, zap.Error(err))
return
}
// Retrieve the file from the form data
file, _, err := r.FormFile("file")
if jc.Check(errRetrievingFile, err) != nil {
h.portal.Logger().Error(errRetrievingFile, zap.Error(err))
return
}
defer func(file multipart.File) {
err := file.Close()
if err != nil {
h.portal.Logger().Error(errClosingStream, zap.Error(err))
}
}(file)
2024-01-15 20:16:48 +00:00
rs = file
2024-01-15 04:54:43 +00:00
} else {
2024-01-15 20:16:48 +00:00
data, err := io.ReadAll(r.Body)
2024-01-15 04:54:43 +00:00
if jc.Check(errReadFile, err) != nil {
h.portal.Logger().Error(errReadFile, zap.Error(err))
return
}
2024-01-15 20:16:48 +00:00
buffer := bytes.NewReader(data)
bufferSize = int64(buffer.Len())
rs = buffer
2024-01-15 04:54:43 +00:00
defer func(Body io.ReadCloser) {
err := Body.Close()
if err != nil {
h.portal.Logger().Error(errClosingStream, zap.Error(err))
}
}(r.Body)
}
2024-01-16 06:05:09 +00:00
hash, err := h.portal.Storage().GetHash(rs)
if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
if exists, upload := h.portal.Storage().FileExists(hash); exists {
cid, err := encoding.CIDFromHash(hash, upload.Size, types.CIDTypeRaw)
if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
cidStr, err := cid.ToString()
if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
jc.Encode(map[string]string{"hash": cidStr})
return
}
hash, err = h.portal.Storage().PutFile(rs, "s5", false)
2024-01-15 04:54:43 +00:00
if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
2024-01-15 20:16:48 +00:00
cid, err := encoding.CIDFromHash(hash, uint64(bufferSize), types.CIDTypeRaw)
2024-01-15 04:54:43 +00:00
if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
cidStr, err := cid.ToString()
if err != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
2024-01-16 07:01:18 +00:00
tx := h.portal.Database().Create(&models.Upload{
Hash: hex.EncodeToString(hash),
Size: uint64(bufferSize),
Protocol: "s5",
UserID: 0,
})
if tx.Error != nil {
_ = jc.Error(errUploadingFileErr, http.StatusInternalServerError)
h.portal.Logger().Error(errUploadingFile, zap.Error(err))
return
}
jc.Encode(&SmallUploadResponse{
CID: cidStr,
})
2024-01-15 04:54:43 +00:00
}
2024-01-16 16:42:50 +00:00
func (h *HttpHandler) AccountRegisterChallenge(jc jape.Context) {
var pubkey string
if jc.DecodeForm("pubKey", &pubkey) != nil {
return
}
challenge := make([]byte, 32)
_, err := rand.Read(challenge)
if err != nil {
_ = jc.Error(errAccountGenerateChallengeErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountGenerateChallenge, zap.Error(err))
return
}
decodedKey, err := base64.RawURLEncoding.DecodeString(pubkey)
if err != nil {
_ = jc.Error(errAccountGenerateChallengeErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountGenerateChallenge, zap.Error(err))
return
}
if len(decodedKey) != 32 {
_ = jc.Error(errAccountGenerateChallengeErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountGenerateChallenge, zap.Error(err))
return
}
result := h.portal.Database().Create(&models.S5Challenge{
Challenge: hex.EncodeToString(challenge),
2024-01-16 18:51:03 +00:00
Type: "register",
})
if result.Error != nil {
_ = jc.Error(errAccountGenerateChallengeErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountGenerateChallenge, zap.Error(err))
return
}
jc.Encode(&AccountRegisterChallengeResponse{
Challenge: base64.RawURLEncoding.EncodeToString(challenge),
})
}
func (h *HttpHandler) AccountRegister(jc jape.Context) {
var request AccountRegisterRequest
if jc.Decode(&request) != nil {
return
}
errored := func(err error) {
_ = jc.Error(errAccountRegisterErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountRegister, zap.Error(err))
}
decodedKey, err := base64.RawURLEncoding.DecodeString(request.Pubkey)
if err != nil {
errored(err)
return
}
if len(decodedKey) != 32 {
errored(err)
return
}
var challenge models.S5Challenge
2024-01-16 18:51:03 +00:00
result := h.portal.Database().Model(&models.S5Challenge{}).Where(&models.S5Challenge{Pubkey: request.Pubkey, Type: "register"}).First(&challenge)
if result.RowsAffected == 0 || result.Error != nil {
errored(err)
return
}
decodedResponse, err := base64.RawURLEncoding.DecodeString(request.Response)
if err != nil {
errored(err)
return
}
if len(decodedResponse) != 64 {
errored(err)
return
}
decodedChallenge, err := base64.RawURLEncoding.DecodeString(challenge.Challenge)
if err != nil {
errored(err)
return
}
if !bytes.Equal(decodedResponse, decodedChallenge) {
errored(errInvalidChallengeErr)
return
}
if int(decodedKey[0]) != int(types.HashTypeEd25519) {
errored(errPubkeyNotSupported)
return
}
decodedSignature, err := base64.RawURLEncoding.DecodeString(request.Signature)
if err != nil {
errored(err)
return
}
if !ed25519.Verify(decodedKey, decodedChallenge, decodedSignature) {
errored(errInvalidSignatureErr)
return
}
verify, _ := h.verifier.Verify(request.Email)
if !verify.Syntax.Valid {
errored(errInvalidEmail)
return
}
accountExists, _ := h.portal.Accounts().EmailExists(request.Email)
if accountExists {
errored(errEmailAlreadyExists)
return
}
pubkeyExists, _ := h.portal.Accounts().PubkeyExists(request.Pubkey)
if pubkeyExists {
errored(errPubkeyAlreadyExists)
return
}
passwd := make([]byte, 32)
_, err = rand.Read(passwd)
if accountExists {
errored(errGeneratingPassword)
return
}
newAccount, err := h.portal.Accounts().CreateAccount(request.Email, string(passwd))
if err != nil {
errored(errAccountRegisterErr)
return
}
err = h.portal.Accounts().AddPubkeyToAccount(*newAccount, request.Pubkey)
if err != nil {
errored(errAccountRegisterErr)
return
}
jwt, err := h.portal.Accounts().LoginPubkey(request.Pubkey)
if err != nil {
errored(errAccountRegisterErr)
return
}
2024-01-16 18:38:10 +00:00
setAuthCookie(jwt, jc)
}
func (h *HttpHandler) AccountLoginChallenge(jc jape.Context) {
2024-01-16 18:51:03 +00:00
var pubkey string
if jc.DecodeForm("pubKey", &pubkey) != nil {
return
}
errored := func(err error) {
_ = jc.Error(errAccountLoginErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountLogin, zap.Error(err))
}
challenge := make([]byte, 32)
_, err := rand.Read(challenge)
if err != nil {
_ = jc.Error(errAccountGenerateChallengeErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountGenerateChallenge, zap.Error(err))
return
}
decodedKey, err := base64.RawURLEncoding.DecodeString(pubkey)
if err != nil {
errored(err)
return
}
if len(decodedKey) != 32 {
errored(err)
return
}
result := h.portal.Database().Create(&models.S5Challenge{
Challenge: hex.EncodeToString(challenge),
Type: "login",
})
if result.Error != nil {
errored(err)
return
}
jc.Encode(&AccountLoginChallengeResponse{
Challenge: base64.RawURLEncoding.EncodeToString(challenge),
})
}
func (h *HttpHandler) AccountLogin(jc jape.Context) {
2024-01-16 18:56:25 +00:00
var request AccountLoginRequest
if jc.Decode(&request) != nil {
return
}
errored := func(err error) {
_ = jc.Error(errAccountLoginErr, http.StatusInternalServerError)
h.portal.Logger().Error(errAccountLogin, zap.Error(err))
}
decodedKey, err := base64.RawURLEncoding.DecodeString(request.Pubkey)
if err != nil {
errored(err)
return
}
if len(decodedKey) != 32 {
errored(err)
return
}
var challenge models.S5Challenge
result := h.portal.Database().Model(&models.S5Challenge{}).Where(&models.S5Challenge{Pubkey: request.Pubkey, Type: "login"}).First(&challenge)
if result.RowsAffected == 0 || result.Error != nil {
errored(err)
return
}
decodedResponse, err := base64.RawURLEncoding.DecodeString(request.Response)
if err != nil {
errored(err)
return
}
if len(decodedResponse) != 64 {
errored(err)
return
}
decodedChallenge, err := base64.RawURLEncoding.DecodeString(challenge.Challenge)
if err != nil {
errored(err)
return
}
if !bytes.Equal(decodedResponse, decodedChallenge) {
errored(errInvalidChallengeErr)
return
}
if int(decodedKey[0]) != int(types.HashTypeEd25519) {
errored(errPubkeyNotSupported)
return
}
decodedSignature, err := base64.RawURLEncoding.DecodeString(request.Signature)
if err != nil {
errored(err)
return
}
if !ed25519.Verify(decodedKey, decodedChallenge, decodedSignature) {
errored(errInvalidSignatureErr)
return
}
jwt, err := h.portal.Accounts().LoginPubkey(request.Pubkey)
if err != nil {
errored(errAccountLoginErr)
return
}
setAuthCookie(jwt, jc)
}
2024-01-16 18:38:10 +00:00
func setAuthCookie(jwt string, jc jape.Context) {
authCookie := http.Cookie{
Name: "s5-auth-token",
Value: jwt,
Path: "/",
HttpOnly: true,
MaxAge: int(time.Hour.Seconds() * 24),
Secure: true,
}
http.SetCookie(jc.ResponseWriter, &authCookie)
}