From d1caa01eb2425e54ac1a28a127e618db986f096c Mon Sep 17 00:00:00 2001
From: RandomChars <random@chars.jp>
Date: Thu, 26 Aug 2021 20:20:09 +0900
Subject: [PATCH] some sanity checking on password set, switch to
 UserSecretPayload in places needed

---
 api.go       | 19 +++++++++++++------
 api/types.go |  4 ++++
 2 files changed, 17 insertions(+), 6 deletions(-)

diff --git a/api.go b/api.go
index 1b5252d..d33080f 100644
--- a/api.go
+++ b/api.go
@@ -9,6 +9,7 @@ import (
 	"random.chars.jp/git/image-board/store"
 	"strconv"
 	"strings"
+	"unicode/utf8"
 )
 
 func registerAPI() {
@@ -154,7 +155,15 @@ func registerAPI() {
 			context.JSON(http.StatusBadRequest, api.Error{Error: err.Error()})
 			return
 		} else {
+			if !utf8.Valid(payload) {
+				context.JSON(http.StatusBadRequest, api.Error{Error: "invalid encoding"})
+				return
+			}
 			newPass = string(payload)
+			if len(newPass) > 8192 || strings.Contains(newPass, "\n") {
+				context.JSON(http.StatusBadRequest, api.Error{Error: "invalid password"})
+				return
+			}
 		}
 
 		if newPass == "" {
@@ -163,9 +172,7 @@ func registerAPI() {
 		}
 
 		instance.UserPasswordUpdate(info.Snowflake, newPass)
-		context.JSON(http.StatusOK, gin.H{
-			"secret": instance.UserSecretRegen(info.Snowflake),
-		})
+		context.JSON(http.StatusOK, api.UserSecretPayload{Secret: instance.UserSecretRegen(info.Snowflake)})
 	})
 
 	router.GET(api.UsernameField, func(context *gin.Context) {
@@ -190,7 +197,7 @@ func registerAPI() {
 
 		username := context.Param("name")
 		if instance.UserUsernamePasswordValidate(username, password) {
-			context.String(http.StatusOK, instance.UserUsername(username).Secret)
+			context.JSON(http.StatusOK, api.UserSecretPayload{Secret: instance.UserUsername(username).Secret})
 		} else {
 			context.JSON(http.StatusForbidden, api.Denied)
 		}
@@ -210,7 +217,7 @@ func registerAPI() {
 			context.JSON(http.StatusForbidden, api.Denied)
 			return
 		}
-		context.String(http.StatusOK, instance.User(flake).Secret)
+		context.JSON(http.StatusOK, api.UserSecretPayload{Secret: instance.User(flake).Secret})
 	})
 
 	router.PUT(api.UserSecret, func(context *gin.Context) {
@@ -227,7 +234,7 @@ func registerAPI() {
 			context.JSON(http.StatusForbidden, api.Denied)
 			return
 		}
-		context.String(http.StatusOK, instance.UserSecretRegen(flake))
+		context.JSON(http.StatusOK, api.UserSecretPayload{Secret: instance.UserSecretRegen(flake)})
 	})
 
 	router.GET(api.UserImage, func(context *gin.Context) {
diff --git a/api/types.go b/api/types.go
index b0ea015..e793626 100644
--- a/api/types.go
+++ b/api/types.go
@@ -16,6 +16,10 @@ type UserUpdatePayload struct {
 	Username string `json:"username"`
 }
 
+type UserSecretPayload struct {
+	Secret string `json:"secret"`
+}
+
 type TagUpdatePayload struct {
 	Type string `json:"type"`
 }
-- 
GitLab