Compare commits

..

47 commits

Author SHA1 Message Date
Ada
833858733c
WIP
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/release Pipeline was successful
2024-03-10 10:31:04 +01:00
Ada
e5e9d1df1d
WIP 2024-03-10 01:53:16 +01:00
Ada
a0e90c4304
📦 Make packaging 2024-03-10 01:20:39 +01:00
Ada
d2262fcced Merge pull request '⬆️ bump x/crypto and x/sys dependancies' (#34) from ada/bump-deps into main
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #34
2024-03-05 18:39:15 +00:00
Ada
e67727b95f
⬆️ bump x/crypto and x/sys dependancies
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/pr/release Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
ci/woodpecker/pull_request_closed/release Pipeline was successful
2024-03-05 19:35:19 +01:00
Ada
1d0034b5c8 Merge pull request '🔒 Add secret token hashing with argon2id' (#31) from ada/hash-token into main
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #31
2024-02-26 21:36:25 +00:00
Ada
f6b48d0ae7
lock: Add secret token hashing with argon2id
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/release Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
ci/woodpecker/pull_request_closed/release Pipeline was successful
2024-02-26 21:46:19 +01:00
Ada
20d24e2446 Merge pull request ' Implement basic POST request for curl' (#30) from ada/curl-upload into main
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #30
2024-02-24 23:36:14 +00:00
Ada
55fcd82834 Merge pull request '🧪 Add test to ParseExpiration when a value is to high' (#33) from ada/more-utils-test into main
Reviewed-on: #33
2024-02-24 23:35:36 +00:00
Ada
3954079b95
🧪 Add test to ParseExpiration when a value is to high 2024-02-25 00:35:11 +01:00
Ada
c360291209 Merge pull request '⬆️ bump go-redis 9.5.1' (#32) from ada/bump-redis into main
Reviewed-on: #32
2024-02-24 23:33:38 +00:00
Ada
cdb7386558
⬆️ bump go-redis 9.5.1 2024-02-25 00:32:26 +01:00
Ada
e99c71cc20
Implement basic POST request for curl
/ can now read body and create paste, for curl like client, web create with full settings is move to /create
2024-02-24 01:35:26 +01:00
Ada
d93c024a0c Merge pull request 'Add redis connection test before start' (#29) from ada/redis-ping into main
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #29
2024-02-22 11:55:34 +00:00
Ada
130a5ee345
Add redis connection test before start
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/pr/release Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pull_request_closed/release Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
2024-02-21 14:34:19 +01:00
Ada
ac2c44252c Merge pull request ' Support filename' (#27) from ada/backend/filename into main
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #27
2024-02-21 12:56:35 +00:00
Ada
9570e339a3
Support filename
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/release Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
ci/woodpecker/pull_request_closed/release Pipeline was successful
2024-02-21 13:51:08 +01:00
Ada
04dad7d5af Merge pull request '♻️ Use math/rand/v2' (#28) from ada/use-rand-v2 into main
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #28
2024-02-21 12:28:39 +00:00
Ada
4257994cab Merge pull request '👷 Add build releases file on tag' (#26) from ada/release into main
Some checks failed
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/push/build Pipeline failed
Reviewed-on: #26
2024-02-21 12:27:20 +00:00
Ada
36e959f5e2
♻️ Use math/rand/v2
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
2024-02-19 00:32:27 +01:00
Ada
6905f63059
👷 Add build releases file on tag
All checks were successful
ci/woodpecker/push/release Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/release Pipeline was successful
ci/woodpecker/pull_request_closed/release Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
2024-02-18 22:31:19 +01:00
Ada
7ac2732d25 Merge pull request '⬆️ bump go-redis 9.5.0' (#25) from ada/bump-redis into main
All checks were successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #25
2024-02-18 20:51:55 +00:00
Ada
900243a766
⬆️ bump go-redis 9.5.0
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
2024-02-18 20:32:07 +01:00
Ada
dfa460b919 Merge pull request '👷 Docker support' (#19) from ada/docker into main
All checks were successful
ci/woodpecker/push/build Pipeline was successful
Reviewed-on: #19
2024-02-18 19:19:29 +00:00
Ada
eaaf09c978
👷 Add docker support and CI related stuff
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pull_request_closed/build Pipeline was successful
2024-02-18 19:05:18 +01:00
Ada
b5a9a3e669
🔧 Supresss automatic .env load
Automatic load of .env is a problem for Docker and not really usefull in other context
2024-02-18 18:55:57 +01:00
Ada
1ef6d3efaf Merge pull request '🏗️ Embed static files in binary' (#22) from ada/embed into main
Reviewed-on: #22
2024-02-18 17:53:13 +00:00
Ada
eeabb76fdb Merge pull request '♻️ Simplifies return condition' (#23) from ada/simplifies-return into main
Reviewed-on: #23
2024-02-18 00:15:17 +00:00
Ada
fb66f654e7 Merge pull request '🐛 fix 404 on first hit' (#21) from ada/fix-404 into main
Reviewed-on: #21
2024-02-18 00:14:13 +00:00
Ada
55a79dbd9d
♻️ Simplifies return condition 2024-02-17 00:32:55 +01:00
Ada
199a926418
🏗️ Embed static files in binary 2024-02-17 00:23:32 +01:00
Ada
9360556006
🐛 fix 404 on first hit
On first hit, Server() calls for the first time router(). As a result / and /static are only configured after first hit
2024-02-16 22:41:29 +01:00
Ada
d5fea70587 Merge pull request '♻️ Move code from main to module' (#18) from ada/refactor into main
Reviewed-on: #18
2024-02-11 23:40:12 +00:00
Ada
021e4a731a
♻️ Move code from main to module & clean code 2024-02-12 00:37:51 +01:00
Ada
df2b918801 Merge pull request '💄 Move DELETE logic to specific function' (#16) from ada/backend/refactor-delete into main
Reviewed-on: #16
2024-01-23 21:28:50 +00:00
Ada
b5a19209b2 💄 Move DELETE logic to specific function 2024-01-23 22:28:19 +01:00
Ada
bf516229da Merge pull request 'bump(go-redis): v9.4.0' (#15) from ada/backend/update-redis into main
Reviewed-on: #15
2024-01-23 21:14:52 +00:00
Ada
d6a015489d bump(go-redis): v9.4.0 2024-01-23 22:13:21 +01:00
Ada
3308d5419c Merge pull request ' Plak expiration support' (#14) from ada/backend/expiration into main
Reviewed-on: #14
2024-01-23 21:02:45 +00:00
Ada
d5610eb24c Plak expiration support 2024-01-23 22:00:06 +01:00
Ada
1731efcc28 Merge pull request 'fix(backend): broken utf8 on raw view' (#13) from fix/raw/utf-8 into main
Reviewed-on: #13
2023-11-26 19:10:56 +00:00
Ada
da1d1a1ef2 fix(backend): broken utf8 on raw view 2023-11-26 02:53:24 +01:00
Akinimaginable
83b4f5fe04 Merge pull request 'features' (#12) from features into main
Reviewed-on: #12
2023-11-25 23:10:29 +00:00
hacki
4b53f0e1d9 Remove IDE specific files 2023-11-26 00:08:47 +01:00
hacki
1c086c5afb Added line counter + some return optimization 2023-11-26 00:00:53 +01:00
Akinimaginable
6567a7c0cd Merge pull request 'clean(backend): make one global redis client' (#10) from clean-db into main
Reviewed-on: #10
2023-11-25 18:18:28 +00:00
Akinimaginable
8dc45aeb01 Merge pull request 'clean(backend): Remove duplicate config example' (#9) from clean-env into main
Reviewed-on: #9
2023-11-25 18:16:16 +00:00
18 changed files with 116 additions and 237 deletions

View file

@ -1,25 +0,0 @@
linters:
enable-all: true
disable:
# Deprecated
- varcheck
- ifshort
- interfacer
- maligned
- deadcode
- scopelint
- golint
- structcheck
- exhaustivestruct
- nosnakecase
# Too extremist/unusable
- depguard
- varnamelen
- exhaustruct
- wsl
- contextcheck
- wrapcheck
linters-settings:
lll:
# Too short byt default
line-length: 160

View file

@ -6,11 +6,7 @@
# yaml-language-server: $schema=https://goreleaser.com/static/schema.json # yaml-language-server: $schema=https://goreleaser.com/static/schema.json
# vim: set ts=2 sw=2 tw=0 fo=cnqoj # vim: set ts=2 sw=2 tw=0 fo=cnqoj
gitea_urls: version: 1
api: https://git.gnous.eu/api/v1
download: https://git.gnous.eu
# set to true if you use a self-signed certificate
skip_tls_verify: false
before: before:
hooks: hooks:
@ -40,6 +36,10 @@ archives:
{{- else if eq .Arch "386" }}i386 {{- else if eq .Arch "386" }}i386
{{- else }}{{ .Arch }}{{ end }} {{- else }}{{ .Arch }}{{ end }}
{{- if .Arm }}v{{ .Arm }}{{ end }} {{- if .Arm }}v{{ .Arm }}{{ end }}
# use zip for windows archives
format_overrides:
- goos: windows
format: zip
nfpms: nfpms:
- -

View file

@ -11,7 +11,22 @@ steps:
from_secret: docker_username from_secret: docker_username
password: password:
from_secret: docker_password from_secret: docker_password
debug: true
when: when:
branch: ${CI_REPO_DEFAULT_BRANCH} branch: ${CI_REPO_DEFAULT_BRANCH}
event: push event: push
- name: publish_image_tag
image: woodpeckerci/plugin-docker-buildx
settings:
repo: git.gnous.eu/${CI_REPO_OWNER}/plakken
dockerfile: docker/Dockerfile
platforms: linux/amd64,linux/arm64/v8,linux/arm
registry: https://git.gnous.eu
tags:
- ${CI_COMMIT_TAG##v} # Remove v from tag
- stable
username:
from_secret: docker_username
password:
from_secret: docker_password
when:
event: tag

View file

@ -1,11 +0,0 @@
steps:
lint:
image: golang:1.22
commands:
- go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
- golangci-lint run
when:
- event: pull_request
repo: gnouseu/plakken
- event: push
branch: main

View file

@ -1,25 +1,8 @@
steps: steps:
- name: Release - name: release
image: golang:1.22 image: goreleaser/goreleaser
commands: commands:
- go install github.com/goreleaser/goreleaser@latest
- goreleaser release - goreleaser release
secrets: [ gitea_token ] secrets: [ release_token ]
when:
event: tag
- name: publish_image_tag
image: woodpeckerci/plugin-docker-buildx
settings:
repo: git.gnous.eu/${CI_REPO_OWNER}/plakken
dockerfile: docker/Dockerfile
platforms: linux/amd64,linux/arm64/v8,linux/arm
registry: https://git.gnous.eu
tags:
- ${CI_COMMIT_TAG##v} # Remove v from tag
- stable
username:
from_secret: docker_username
password:
from_secret: docker_password
when: when:
event: tag event: tag

6
go.mod
View file

@ -4,11 +4,11 @@ go 1.22
require ( require (
github.com/redis/go-redis/v9 v9.5.1 github.com/redis/go-redis/v9 v9.5.1
golang.org/x/crypto v0.22.0 golang.org/x/crypto v0.21.0
) )
require ( require (
github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
golang.org/x/sys v0.19.0 // indirect golang.org/x/sys v0.18.0 // indirect
) )

12
go.sum
View file

@ -2,13 +2,13 @@ github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c= github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA= github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0= github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8= github.com/redis/go-redis/v9 v9.5.1 h1:H1X4D3yHPaYrkL5X06Wh6xNVM/pX0Ft4RV0vMGvLBh8=
github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M= github.com/redis/go-redis/v9 v9.5.1/go.mod h1:hdY0cQFCN4fnSYT6TkisLufl/4W5UIXyv0b/CLO2V2M=
golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
golang.org/x/sys v0.19.0 h1:q5f1RH2jigJ1MoAWp2KTp3gm5zAGFUTarQZ5U386+4o= golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
golang.org/x/sys v0.19.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

View file

@ -4,21 +4,19 @@ import (
"log" "log"
"os" "os"
"strconv" "strconv"
"git.gnous.eu/gnouseu/plakken/internal/constant"
) )
// InitConfig Structure for program initialisation. // InitConfig Structure for program initialisation
type InitConfig struct { type InitConfig struct {
ListenAddress string ListenAddress string
RedisAddress string RedisAddress string
RedisUser string RedisUser string
RedisPassword string RedisPassword string
RedisDB int RedisDB int
URLLength uint8 UrlLength uint8
} }
// GetConfig Initialise configuration form .env. // GetConfig Initialise configuration form .env
func GetConfig() InitConfig { func GetConfig() InitConfig {
listenAddress := os.Getenv("PLAKKEN_LISTEN") listenAddress := os.Getenv("PLAKKEN_LISTEN")
redisAddress := os.Getenv("PLAKKEN_REDIS_ADDRESS") redisAddress := os.Getenv("PLAKKEN_REDIS_ADDRESS")
@ -39,7 +37,7 @@ func GetConfig() InitConfig {
log.Fatal("Invalid PLAKKEN_URL_LENGTH") log.Fatal("Invalid PLAKKEN_URL_LENGTH")
} }
if urlLength > constant.MaxURLLength { if urlLength > 255 {
log.Fatal("PLAKKEN_URL_LENGTH cannot be greater than 255") log.Fatal("PLAKKEN_URL_LENGTH cannot be greater than 255")
} }
@ -49,6 +47,6 @@ func GetConfig() InitConfig {
RedisUser: os.Getenv("PLAKKEN_REDIS_USER"), RedisUser: os.Getenv("PLAKKEN_REDIS_USER"),
RedisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"), RedisPassword: os.Getenv("PLAKKEN_REDIS_PASSWORD"),
RedisDB: redisDB, RedisDB: redisDB,
URLLength: uint8(urlLength), UrlLength: uint8(urlLength),
} }
} }

View file

@ -11,8 +11,4 @@ const (
ArgonThreads = 4 ArgonThreads = 4
ArgonKeyLength = 32 ArgonKeyLength = 32
ArgonIterations = 2 ArgonIterations = 2
MaxURLLength = 255
SecondsInDay = 86400
SecondsInHour = 3600
SecondsInMinute = 60
) )

View file

@ -13,9 +13,9 @@ type DBConfig struct {
DB *redis.Client DB *redis.Client
} }
var ctx = context.Background() //nolint:gochecknoglobals var ctx = context.Background()
// InitDB initialise redis connection settings. // InitDB initialise redis connection settings
func InitDB(addr string, user string, password string, db int) *redis.Options { func InitDB(addr string, user string, password string, db int) *redis.Options {
DBConfig := &redis.Options{ DBConfig := &redis.Options{
Addr: addr, Addr: addr,
@ -27,20 +27,18 @@ func InitDB(addr string, user string, password string, db int) *redis.Options {
return DBConfig return DBConfig
} }
// ConnectDB make new database connection. // ConnectDB make new database connection
func ConnectDB(dbConfig *redis.Options) *redis.Client { func ConnectDB(dbConfig *redis.Options) *redis.Client {
localDB := redis.NewClient(dbConfig) localDb := redis.NewClient(dbConfig)
return localDb
return localDB
} }
// Ping test connection to Redis database. // Ping test connection to Redis database
func Ping(db *redis.Client) error { func Ping(db *redis.Client) error {
status := db.Ping(ctx) status := db.Ping(ctx)
if status.String() != "ping: PONG" { if status.String() != "ping: PONG" {
return &pingError{} return &pingError{}
} }
return nil return nil
} }
@ -67,7 +65,7 @@ func (config DBConfig) InsertPaste(key string, content string, secret string, tt
} }
} }
func (config DBConfig) URLExist(url string) bool { func (config DBConfig) UrlExist(url string) bool {
return config.DB.Exists(ctx, url).Val() == 1 return config.DB.Exists(ctx, url).Val() == 1
} }

View file

@ -1,4 +1,4 @@
package httpserver package httpServer
import ( import (
"embed" "embed"
@ -12,7 +12,7 @@ import (
type ServerConfig struct { type ServerConfig struct {
HTTPServer *http.Server HTTPServer *http.Server
URLLength uint8 UrlLength uint8
DB *redis.Client DB *redis.Client
Static embed.FS Static embed.FS
Templates embed.FS Templates embed.FS
@ -29,11 +29,11 @@ func (config ServerConfig) home(w http.ResponseWriter, _ *http.Request) {
} }
} }
// Configure HTTP router. // Configure HTTP router
func (config ServerConfig) router() { func (config ServerConfig) router() {
WebConfig := plak.WebConfig{ WebConfig := plak.WebConfig{
DB: config.DB, DB: config.DB,
URLLength: config.URLLength, UrlLength: config.UrlLength,
Templates: config.Templates, Templates: config.Templates,
} }
staticFiles := http.FS(config.Static) staticFiles := http.FS(config.Static)
@ -46,7 +46,7 @@ func (config ServerConfig) router() {
http.HandleFunc("DELETE /{key}", WebConfig.DeleteRequest) http.HandleFunc("DELETE /{key}", WebConfig.DeleteRequest)
} }
// Config Configure HTTP server. // Config Configure HTTP server
func Config(listenAddress string) *http.Server { func Config(listenAddress string) *http.Server {
server := &http.Server{ server := &http.Server{
Addr: listenAddress, Addr: listenAddress,
@ -57,7 +57,7 @@ func Config(listenAddress string) *http.Server {
return server return server
} }
// Server Start HTTP server. // Server Start HTTP server
func (config ServerConfig) Server() { func (config ServerConfig) Server() {
log.Println("Listening on " + config.HTTPServer.Addr) log.Println("Listening on " + config.HTTPServer.Addr)

View file

@ -5,7 +5,6 @@ import (
"bytes" "bytes"
"crypto/rand" "crypto/rand"
"encoding/base64" "encoding/base64"
"encoding/hex"
"fmt" "fmt"
"strconv" "strconv"
"strings" "strings"
@ -19,7 +18,7 @@ type argon2idHash struct {
hash []byte hash []byte
} }
// Argon2id config. // Argon2id config
type config struct { type config struct {
saltLength uint8 saltLength uint8
memory uint32 memory uint32
@ -28,7 +27,7 @@ type config struct {
iterations uint32 iterations uint32
} }
// generateSecret for password hashing or token generation. // generateSecret for password hashing or token generation
func generateSecret(length uint8) ([]byte, error) { func generateSecret(length uint8) ([]byte, error) {
secret := make([]byte, length) secret := make([]byte, length)
@ -40,26 +39,26 @@ func generateSecret(length uint8) ([]byte, error) {
return secret, err return secret, err
} }
// GenerateToken generate hexadecimal token. // GenerateToken generate hexadecimal token
func GenerateToken() (string, error) { func GenerateToken() (string, error) {
secret, err := generateSecret(constant.TokenLength) secret, err := generateSecret(constant.TokenLength)
if err != nil { if err != nil {
return "", err return "", err
} }
token := hex.EncodeToString(secret) token := fmt.Sprintf("%x", secret)
return token, nil return token, nil
} }
// generateArgon2ID Generate an argon2id hash from source string and specified salt. // generateArgon2ID Generate an argon2id hash from source string and specified salt
func (config config) generateArgon2ID(source string, salt []byte) []byte { func (config config) generateArgon2ID(source string, salt []byte) []byte {
hash := argon2.IDKey([]byte(source), salt, config.iterations, config.memory, config.threads, config.keyLength) hash := argon2.IDKey([]byte(source), salt, config.iterations, config.memory, config.threads, config.keyLength)
return hash return hash
} }
// Password hash a source string with argon2id, return properly encoded hash. // Password hash a source string with argon2id, return properly encoded hash
func Password(password string) (string, error) { func Password(password string) (string, error) {
config := config{ config := config{
saltLength: constant.ArgonSaltSize, saltLength: constant.ArgonSaltSize,
@ -96,10 +95,10 @@ func VerifyPassword(password string, hash string) (bool, error) {
return bytes.Equal(result, argon2Hash.hash), nil return bytes.Equal(result, argon2Hash.hash), nil
} }
// parseHash parse existing encoded argon2id string. // parseHash parse existing encoded argon2id string
func parseHash(source string) (argon2idHash, config, error) { func parseHash(source string) (argon2idHash, config, error) {
separateItem := strings.Split(source, "$") separateItem := strings.Split(source, "$")
if len(separateItem) != 6 { //nolint:gomnd if len(separateItem) != 6 {
return argon2idHash{}, config{}, &parseError{message: "Hash format is not valid"} return argon2idHash{}, config{}, &parseError{message: "Hash format is not valid"}
} }
@ -108,7 +107,7 @@ func parseHash(source string) (argon2idHash, config, error) {
} }
separateParam := strings.Split(separateItem[3], ",") separateParam := strings.Split(separateItem[3], ",")
if len(separateParam) != 3 { //nolint:gomnd if len(separateParam) != 3 {
return argon2idHash{}, config{}, &parseError{message: "Hash config is not valid"} return argon2idHash{}, config{}, &parseError{message: "Hash config is not valid"}
} }
@ -127,35 +126,22 @@ func parseHash(source string) (argon2idHash, config, error) {
keyLength := uint32(len(hash)) keyLength := uint32(len(hash))
var memory int var memory int
memory, err = strconv.Atoi(strings.ReplaceAll(separateParam[0], "m=", "")) memory, err = strconv.Atoi(strings.Replace(separateParam[0], "m=", "", -1))
if err != nil { if err != nil {
return argon2idHash{}, config{}, err return argon2idHash{}, config{}, err
} }
var iterations int var iterations int
iterations, err = strconv.Atoi(strings.ReplaceAll(separateParam[1], "t=", "")) iterations, err = strconv.Atoi(strings.Replace(separateParam[1], "t=", "", -1))
if err != nil { if err != nil {
return argon2idHash{}, config{}, err return argon2idHash{}, config{}, err
} }
var threads int var threads int
threads, err = strconv.Atoi(strings.ReplaceAll(separateParam[2], "p=", "")) threads, err = strconv.Atoi(strings.Replace(separateParam[2], "p=", "", -1))
if err != nil { if err != nil {
return argon2idHash{}, config{}, err return argon2idHash{}, config{}, err
} }
argon2idStruct := argon2idHash{ return argon2idHash{salt: salt, hash: hash}, config{saltLength: saltLength, memory: uint32(memory), threads: uint8(threads), iterations: uint32(iterations), keyLength: keyLength}, nil
salt: salt,
hash: hash,
}
hashConfig := config{
saltLength: saltLength,
memory: uint32(memory),
threads: uint8(threads),
iterations: uint32(iterations),
keyLength: keyLength,
}
return argon2idStruct, hashConfig, nil
} }

View file

@ -6,12 +6,10 @@ import (
"regexp" "regexp"
"strconv" "strconv"
"strings" "strings"
"git.gnous.eu/gnouseu/plakken/internal/constant"
) )
// GenerateURL generate random string for plak url. // GenerateUrl generate random string for plak url
func GenerateURL(length uint8) string { func GenerateUrl(length uint8) string {
listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") listChars := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
b := make([]rune, length) b := make([]rune, length)
for i := range b { for i := range b {
@ -21,7 +19,7 @@ func GenerateURL(length uint8) string {
return string(b) return string(b)
} }
// CheckCharRedundant verify is a character is redundant in a string. // CheckCharRedundant verify is a character is redundant in a string
func CheckCharRedundant(source string, char string) bool { // Verify if a char is redundant func CheckCharRedundant(source string, char string) bool { // Verify if a char is redundant
return strings.Count(source, char) > 1 return strings.Count(source, char) > 1
} }
@ -36,24 +34,22 @@ func parseIntBeforeSeparator(source *string, sep string) (int, error) { // retur
value, err = strconv.Atoi(strings.Split(*source, sep)[0]) value, err = strconv.Atoi(strings.Split(*source, sep)[0])
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &parseIntBeforeSeparatorError{message: *source + ": cannot parse value as int"} return 0, &parseIntBeforeSeparatorError{message: *source + ": cannot parse value as int"}
} }
if value < 0 { // Only positive value is correct if value < 0 { // Only positive value is correct
return 0, &parseIntBeforeSeparatorError{message: *source + ": format only take positive value"} return 0, &parseIntBeforeSeparatorError{message: *source + ": format only take positive value"}
} }
if value > 99 { //nolint:gomnd if value > 99 {
return 0, &parseIntBeforeSeparatorError{message: *source + ": Format only take two number"} return 0, &parseIntBeforeSeparatorError{message: *source + ": Format only take two number"}
} }
*source = strings.Join(strings.Split(*source, sep)[1:], "") *source = strings.Join(strings.Split(*source, sep)[1:], "")
} }
return value, nil return value, nil
} }
// ParseExpiration Parse "1d1h1m1s" duration format. Return 0 & error if error. // ParseExpiration Parse "1d1h1m1s" duration format. Return 0 & error if error
func ParseExpiration(source string) (int, error) { func ParseExpiration(source string) (int, error) {
var expiration int var expiration int
var tempOutput int var tempOutput int
@ -65,44 +61,39 @@ func ParseExpiration(source string) (int, error) {
source = strings.ToLower(source) source = strings.ToLower(source)
tempOutput, err = parseIntBeforeSeparator(&source, "d") tempOutput, err = parseIntBeforeSeparator(&source, "d")
expiration = tempOutput * constant.SecondsInDay expiration = tempOutput * 86400
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{message: "Invalid syntax"} return 0, &ParseExpirationError{message: "Invalid syntax"}
} }
tempOutput, err = parseIntBeforeSeparator(&source, "h") tempOutput, err = parseIntBeforeSeparator(&source, "h")
expiration += tempOutput * constant.SecondsInHour expiration += tempOutput * 3600
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{message: "Invalid syntax"} return 0, &ParseExpirationError{message: "Invalid syntax"}
} }
tempOutput, err = parseIntBeforeSeparator(&source, "m") tempOutput, err = parseIntBeforeSeparator(&source, "m")
expiration += tempOutput * constant.SecondsInMinute expiration += tempOutput * 60
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{message: "Invalid syntax"} return 0, &ParseExpirationError{message: "Invalid syntax"}
} }
tempOutput, err = parseIntBeforeSeparator(&source, "s") tempOutput, err = parseIntBeforeSeparator(&source, "s")
expiration += tempOutput * 1 expiration += tempOutput * 1
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return 0, &ParseExpirationError{message: "Invalid syntax"} return 0, &ParseExpirationError{message: "Invalid syntax"}
} }
return expiration, nil return expiration, nil
} }
// ValidKey Verify if a key is valid (only letter, number, - and _). // ValidKey Verify if a key is valid (only letter, number, - and _)
func ValidKey(key string) bool { func ValidKey(key string) bool {
result, err := regexp.MatchString("^[a-zA-Z0-9_.-]*$", key) result, err := regexp.MatchString("^[a-zA-Z0-9_.-]*$", key)
if err != nil { if err != nil {
return false return false
} }
log.Println(key, result) log.Println(key, result)
return result return result
} }

View file

@ -3,7 +3,6 @@ package plak
import ( import (
"context" "context"
"embed" "embed"
"html/template"
"io" "io"
"log" "log"
"net/http" "net/http"
@ -14,17 +13,19 @@ import (
"git.gnous.eu/gnouseu/plakken/internal/secret" "git.gnous.eu/gnouseu/plakken/internal/secret"
"git.gnous.eu/gnouseu/plakken/internal/utils" "git.gnous.eu/gnouseu/plakken/internal/utils"
"github.com/redis/go-redis/v9" "github.com/redis/go-redis/v9"
"html/template"
) )
var ctx = context.Background() //nolint:gochecknoglobals var ctx = context.Background()
type WebConfig struct { type WebConfig struct {
DB *redis.Client DB *redis.Client
URLLength uint8 UrlLength uint8
Templates embed.FS Templates embed.FS
} }
// plak "Object" for plak. // plak "Object" for plak
type plak struct { type plak struct {
Key string Key string
Content string Content string
@ -32,7 +33,7 @@ type plak struct {
DB *redis.Client DB *redis.Client
} }
// create a plak. // create a plak
func (plak plak) create() (string, error) { func (plak plak) create() (string, error) {
dbConf := database.DBConfig{ dbConf := database.DBConfig{
DB: plak.DB, DB: plak.DB,
@ -43,7 +44,7 @@ func (plak plak) create() (string, error) {
return "", err return "", err
} }
if dbConf.URLExist(plak.Key) { if dbConf.UrlExist(plak.Key) {
return "", &createError{message: "key already exist"} return "", &createError{message: "key already exist"}
} }
@ -58,23 +59,21 @@ func (plak plak) create() (string, error) {
return token, nil return token, nil
} }
// PostCreate manage POST request for create plak. // PostCreate manage POST request for create plak
func (config WebConfig) PostCreate(w http.ResponseWriter, r *http.Request) { func (config WebConfig) PostCreate(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content") content := r.FormValue("content")
if content == "" { if content == "" {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
filename := r.FormValue("filename") filename := r.FormValue("filename")
var key string var key string
if len(filename) == 0 { if len(filename) == 0 {
key = utils.GenerateURL(config.URLLength) key = utils.GenerateUrl(config.UrlLength)
} else { } else {
if !utils.ValidKey(filename) { if !utils.ValidKey(filename) {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
key = filename key = filename
@ -91,7 +90,6 @@ func (config WebConfig) PostCreate(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
log.Println(err) log.Println(err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
@ -105,18 +103,16 @@ func (config WebConfig) PostCreate(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
log.Println(err) log.Println(err)
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
return return
} }
http.Redirect(w, r, "/"+key, http.StatusSeeOther) http.Redirect(w, r, "/"+key, http.StatusSeeOther)
} }
// CurlCreate PostCreate plak with minimum param, ideal for curl. Force 7 day expiration. // CurlCreate PostCreate plak with minimum param, ideal for curl. Force 7 day expiration
func (config WebConfig) CurlCreate(w http.ResponseWriter, r *http.Request) { func (config WebConfig) CurlCreate(w http.ResponseWriter, r *http.Request) {
if r.ContentLength == 0 { if r.ContentLength == 0 {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
@ -126,7 +122,7 @@ func (config WebConfig) CurlCreate(w http.ResponseWriter, r *http.Request) {
log.Println(err) log.Println(err)
} }
key := utils.GenerateURL(config.URLLength) key := utils.GenerateUrl(config.UrlLength)
plak := plak{ plak := plak{
Key: key, Key: key,
@ -139,7 +135,6 @@ func (config WebConfig) CurlCreate(w http.ResponseWriter, r *http.Request) {
token, err = plak.create() token, err = plak.create()
if err != nil { if err != nil {
w.WriteHeader(http.StatusBadRequest) w.WriteHeader(http.StatusBadRequest)
return return
} }
@ -159,7 +154,7 @@ func (config WebConfig) CurlCreate(w http.ResponseWriter, r *http.Request) {
} }
} }
// View for plak. // View for plak
func (config WebConfig) View(w http.ResponseWriter, r *http.Request) { func (config WebConfig) View(w http.ResponseWriter, r *http.Request) {
dbConf := database.DBConfig{ dbConf := database.DBConfig{
DB: config.DB, DB: config.DB,
@ -167,8 +162,7 @@ func (config WebConfig) View(w http.ResponseWriter, r *http.Request) {
var currentPlak plak var currentPlak plak
key := r.PathValue("key") key := r.PathValue("key")
//nolint:nestif if dbConf.UrlExist(key) {
if dbConf.URLExist(key) {
currentPlak = plak{ currentPlak = plak{
Key: key, Key: key,
DB: config.DB, DB: config.DB,
@ -185,14 +179,12 @@ func (config WebConfig) View(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
log.Println(err) log.Println(err)
return return
} }
err = t.Execute(w, currentPlak) err = t.Execute(w, currentPlak)
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
log.Println(err) log.Println(err)
return return
} }
} }
@ -201,7 +193,7 @@ func (config WebConfig) View(w http.ResponseWriter, r *http.Request) {
} }
} }
// DeleteRequest manage plak deletion endpoint. // DeleteRequest manage plak deletion endpoint
func (config WebConfig) DeleteRequest(w http.ResponseWriter, r *http.Request) { func (config WebConfig) DeleteRequest(w http.ResponseWriter, r *http.Request) {
dbConf := database.DBConfig{ dbConf := database.DBConfig{
DB: config.DB, DB: config.DB,
@ -209,8 +201,7 @@ func (config WebConfig) DeleteRequest(w http.ResponseWriter, r *http.Request) {
key := r.PathValue("key") key := r.PathValue("key")
var valid bool var valid bool
//nolint:nestif if dbConf.UrlExist(key) {
if dbConf.URLExist(key) {
var err error var err error
token := r.URL.Query().Get("secret") token := r.URL.Query().Get("secret")
@ -218,6 +209,7 @@ func (config WebConfig) DeleteRequest(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
w.WriteHeader(http.StatusInternalServerError) w.WriteHeader(http.StatusInternalServerError)
log.Println(err) log.Println(err)
return
} }
if valid { if valid {
@ -231,31 +223,29 @@ func (config WebConfig) DeleteRequest(w http.ResponseWriter, r *http.Request) {
} }
w.WriteHeader(http.StatusNoContent) w.WriteHeader(http.StatusNoContent)
return
} else { } else {
w.WriteHeader(http.StatusForbidden) w.WriteHeader(http.StatusForbidden)
return
} }
return
} }
w.WriteHeader(http.StatusNotFound) w.WriteHeader(http.StatusNotFound)
} }
// delete DeleteRequest plak from database. // delete DeleteRequest plak from database
func (plak plak) delete() error { func (plak plak) delete() error {
err := plak.DB.Del(ctx, plak.Key).Err() err := plak.DB.Del(ctx, plak.Key).Err()
if err != nil { if err != nil {
log.Println(err) log.Println(err)
return &deletePlakError{name: plak.Key, err: err} return &deletePlakError{name: plak.Key, err: err}
} }
return nil return nil
} }
// getContent get plak content. // getContent get plak content
func (plak plak) getContent() plak { func (plak plak) getContent() plak {
plak.Content = plak.DB.HGet(ctx, plak.Key, "content").Val() plak.Content = plak.DB.HGet(ctx, plak.Key, "content").Val()
return plak return plak
} }

View file

@ -6,7 +6,7 @@ import (
"git.gnous.eu/gnouseu/plakken/internal/config" "git.gnous.eu/gnouseu/plakken/internal/config"
"git.gnous.eu/gnouseu/plakken/internal/database" "git.gnous.eu/gnouseu/plakken/internal/database"
"git.gnous.eu/gnouseu/plakken/internal/httpserver" "git.gnous.eu/gnouseu/plakken/internal/httpServer"
) )
var ( var (
@ -25,9 +25,9 @@ func main() {
log.Fatal(err) log.Fatal(err)
} }
serverConfig := httpserver.ServerConfig{ serverConfig := httpServer.ServerConfig{
HTTPServer: httpserver.Config(initConfig.ListenAddress), HTTPServer: httpServer.Config(initConfig.ListenAddress),
URLLength: initConfig.URLLength, UrlLength: initConfig.UrlLength,
DB: db, DB: db,
Static: static, Static: static,
Templates: templates, Templates: templates,

View file

@ -1,3 +0,0 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json"
}

View file

@ -10,17 +10,8 @@ import (
"golang.org/x/crypto/argon2" "golang.org/x/crypto/argon2"
) )
func TestSecret(t *testing.T) { func TestPasswordFormat(t *testing.T) {
t.Parallel() regex := fmt.Sprintf("\\$argon2id\\$v=%d\\$m=%d,t=%d,p=%d\\$[A-Za-z0-9+/]*\\$[A-Za-z0-9+/]*$", argon2.Version, constant.ArgonMemory, constant.ArgonIterations, constant.ArgonThreads)
testPasswordFormat(t)
testVerifyPassword(t)
testVerifyPasswordInvalid(t)
}
func testPasswordFormat(t *testing.T) {
t.Helper()
regex := fmt.Sprintf("\\$argon2id\\$v=%d\\$m=%d,t=%d,p=%d\\$[A-Za-z0-9+/]*\\$[A-Za-z0-9+/]*$", argon2.Version, constant.ArgonMemory, constant.ArgonIterations, constant.ArgonThreads) //nolint:lll
got, err := secret.Password("Password!") got, err := secret.Password("Password!")
if err != nil { if err != nil {
@ -33,9 +24,8 @@ func testPasswordFormat(t *testing.T) {
} }
} }
func testVerifyPassword(t *testing.T) { func TestVerifyPassword(t *testing.T) {
t.Helper() result, err := secret.VerifyPassword("Password!", "$argon2id$v=19$m=65536,t=2,p=4$A+t5YGpyy1BHCbvk/LP1xQ$eNuUj6B2ZqXlGi6KEqep39a7N4nysUIojuPXye+Ypp0")
result, err := secret.VerifyPassword("Password!", "$argon2id$v=19$m=65536,t=2,p=4$A+t5YGpyy1BHCbvk/LP1xQ$eNuUj6B2ZqXlGi6KEqep39a7N4nysUIojuPXye+Ypp0") //nolint:lll
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@ -45,9 +35,8 @@ func testVerifyPassword(t *testing.T) {
} }
} }
func testVerifyPasswordInvalid(t *testing.T) { func TestVerifyPasswordInvalid(t *testing.T) {
t.Helper() result, err := secret.VerifyPassword("notsamepassword", "$argon2id$v=19$m=65536,t=2,p=4$A+t5YGpyy1BHCbvk/LP1xQ$eNuUj6B2ZqXlGi6KEqep39a7N4nysUIojuPXye+Ypp0")
result, err := secret.VerifyPassword("notsamepassword", "$argon2id$v=19$m=65536,t=2,p=4$A+t5YGpyy1BHCbvk/LP1xQ$eNuUj6B2ZqXlGi6KEqep39a7N4nysUIojuPXye+Ypp0") //nolint:lll
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }

View file

@ -7,25 +7,7 @@ import (
"git.gnous.eu/gnouseu/plakken/internal/utils" "git.gnous.eu/gnouseu/plakken/internal/utils"
) )
func TestUtils(t *testing.T) { func TestCheckCharNotRedundantTrue(t *testing.T) { // Test CheckCharRedundant with redundant char
t.Parallel()
testCheckCharNotRedundantTrue(t)
testCheckCharNotRedundantFalse(t)
testParseExpirationFull(t)
testParseExpirationMissing(t)
testParseExpirationWithCaps(t)
testParseExpirationNull(t)
testParseExpirationNegative(t)
testParseExpirationInvalid(t)
testParseExpirationInvalidRedundant(t)
testParseExpirationInvalidTooHigh(t)
testValidKey(t)
testInValidKey(t)
}
func testCheckCharNotRedundantTrue(t *testing.T) { // Test CheckCharRedundant with redundant char
t.Helper()
want := true want := true
got := utils.CheckCharRedundant("2d1h3md4h7s", "h") got := utils.CheckCharRedundant("2d1h3md4h7s", "h")
if got != want { if got != want {
@ -33,8 +15,7 @@ func testCheckCharNotRedundantTrue(t *testing.T) { // Test CheckCharRedundant wi
} }
} }
func testCheckCharNotRedundantFalse(t *testing.T) { // Test CheckCharRedundant with not redundant char func TestCheckCharNotRedundantFalse(t *testing.T) { // Test CheckCharRedundant with not redundant char
t.Helper()
want := false want := false
got := utils.CheckCharRedundant("2d1h3m47s", "h") got := utils.CheckCharRedundant("2d1h3m47s", "h")
if got != want { if got != want {
@ -42,8 +23,7 @@ func testCheckCharNotRedundantFalse(t *testing.T) { // Test CheckCharRedundant w
} }
} }
func testParseExpirationFull(t *testing.T) { // test parseExpirationFull with all valid separator func TestParseExpirationFull(t *testing.T) { // test parseExpirationFull with all valid separator
t.Helper()
result, _ := utils.ParseExpiration("2d1h3m47s") result, _ := utils.ParseExpiration("2d1h3m47s")
correctValue := 176627 correctValue := 176627
if result != correctValue { if result != correctValue {
@ -51,8 +31,7 @@ func testParseExpirationFull(t *testing.T) { // test parseExpirationFull with al
} }
} }
func testParseExpirationMissing(t *testing.T) { // test parseExpirationFull with all valid separator func TestParseExpirationMissing(t *testing.T) { // test parseExpirationFull with all valid separator
t.Helper()
result, _ := utils.ParseExpiration("1h47s") result, _ := utils.ParseExpiration("1h47s")
correctValue := 3647 correctValue := 3647
if result != correctValue { if result != correctValue {
@ -60,8 +39,7 @@ func testParseExpirationMissing(t *testing.T) { // test parseExpirationFull with
} }
} }
func testParseExpirationWithCaps(t *testing.T) { // test parseExpirationFull with all valid separator func TestParseExpirationWithCaps(t *testing.T) { // test parseExpirationFull with all valid separator
t.Helper()
result, _ := utils.ParseExpiration("2D1h3M47s") result, _ := utils.ParseExpiration("2D1h3M47s")
correctValue := 176627 correctValue := 176627
if result != correctValue { if result != correctValue {
@ -69,8 +47,7 @@ func testParseExpirationWithCaps(t *testing.T) { // test parseExpirationFull wit
} }
} }
func testParseExpirationNull(t *testing.T) { // test ParseExpirationFull with all valid separator func TestParseExpirationNull(t *testing.T) { // test ParseExpirationFull with all valid separator
t.Helper()
result, _ := utils.ParseExpiration("0") result, _ := utils.ParseExpiration("0")
correctValue := 0 correctValue := 0
if result != correctValue { if result != correctValue {
@ -78,8 +55,7 @@ func testParseExpirationNull(t *testing.T) { // test ParseExpirationFull with al
} }
} }
func testParseExpirationNegative(t *testing.T) { // test ParseExpirationFull with all valid separator func TestParseExpirationNegative(t *testing.T) { // test ParseExpirationFull with all valid separator
t.Helper()
_, got := utils.ParseExpiration("-42h1m4s") _, got := utils.ParseExpiration("-42h1m4s")
want := &utils.ParseExpirationError{} want := &utils.ParseExpirationError{}
if !errors.As(got, &want) { if !errors.As(got, &want) {
@ -87,17 +63,16 @@ func testParseExpirationNegative(t *testing.T) { // test ParseExpirationFull wit
} }
} }
func testParseExpirationInvalid(t *testing.T) { // test ParseExpirationFull with all valid separator func TestParseExpirationInvalid(t *testing.T) { // test ParseExpirationFull with all valid separator
t.Helper()
_, got := utils.ParseExpiration("8h42h1m1d4s") _, got := utils.ParseExpiration("8h42h1m1d4s")
want := &utils.ParseExpirationError{} want := &utils.ParseExpirationError{}
if !errors.As(got, &want) { if !errors.As(got, &want) {
t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got) t.Fatal("Error in ParseExpirationFull, want : ", want, "got : ", got)
} }
} }
func testParseExpirationInvalidRedundant(t *testing.T) { // test ParseExpirationFull with all valid separator func TestParseExpirationInvalidRedundant(t *testing.T) { // test ParseExpirationFull with all valid separator
t.Helper()
_, got := utils.ParseExpiration("8h42h1m1h4s") _, got := utils.ParseExpiration("8h42h1m1h4s")
want := &utils.ParseExpirationError{} want := &utils.ParseExpirationError{}
if !errors.As(got, &want) { if !errors.As(got, &want) {
@ -105,8 +80,7 @@ func testParseExpirationInvalidRedundant(t *testing.T) { // test ParseExpiration
} }
} }
func testParseExpirationInvalidTooHigh(t *testing.T) { // test ParseExpirationFull with all valid separator func TestParseExpirationInvalidTooHigh(t *testing.T) { // test ParseExpirationFull with all valid separator
t.Helper()
_, got := utils.ParseExpiration("2d1h3m130s") _, got := utils.ParseExpiration("2d1h3m130s")
want := &utils.ParseExpirationError{} want := &utils.ParseExpirationError{}
if !errors.As(got, &want) { if !errors.As(got, &want) {
@ -114,8 +88,7 @@ func testParseExpirationInvalidTooHigh(t *testing.T) { // test ParseExpirationFu
} }
} }
func testValidKey(t *testing.T) { // test ValidKey with a valid key func TestValidKey(t *testing.T) { // test ValidKey with a valid key
t.Helper()
got := utils.ValidKey("ab_a-C42") got := utils.ValidKey("ab_a-C42")
want := true want := true
@ -124,8 +97,7 @@ func testValidKey(t *testing.T) { // test ValidKey with a valid key
} }
} }
func testInValidKey(t *testing.T) { // test ValidKey with invalid key func TestInValidKey(t *testing.T) { // test ValidKey with invalid key
t.Helper()
got := utils.ValidKey("ab_?a-C42") got := utils.ValidKey("ab_?a-C42")
want := false want := false