linstrom/web/shared/client.go
mStar 5e13817563
All checks were successful
/ docker (push) Successful in 4m9s
IT FUCKING WORKS
(except for iceshrimp, but who cares) (well, I do. Would not be nice to
not be compatible with a not-so-rarely used software)
2025-04-14 23:14:30 +02:00

80 lines
2.2 KiB
Go

package webshared
import (
"io"
"net/http"
"strings"
"time"
"git.mstar.dev/mstar/goutils/maputils"
"git.mstar.dev/mstar/linstrom/config"
)
// No init needed, zero value is good
var RequestClient = http.Client{}
// Sign a given outbound request for authorized fetch.
// At the end, the Signature header will have the signature needed,
// nothing else is modified.
// If the request is POST, the postBody must contain the raw body of
// the request and the Digest header will also be added
func SignRequest(r *http.Request, keyId string, privateKeyBytes, postBody []byte) error {
method := r.Method
headers := r.Header
if dateString := headers.Get("Date"); dateString != "" {
} else {
headers.Set("Date", time.Now().UTC().Format(http.TimeFormat))
}
applyBodyHash(headers, postBody)
mappedHeaders := maputils.MapNewKeys(headers, func(k string, v []string) (string, string) {
if len(v) > 0 {
return strings.ToLower(k), v[0]
} else {
return strings.ToLower(k), ""
}
})
// Filter for only the date, host, digest and request-target headers
mappedHeaders = maputils.FilterMap(mappedHeaders, func(k, v string) bool {
k = strings.ToLower(k)
return k == "date" || k == "host" || k == "digest" || k == "(request-target)"
})
var signedString string
var usedHeaders []string
if config.GlobalConfig.Experimental.UseEd25519Keys {
tmp, tmp2, err := CreateSignatureED(method, r.URL, mappedHeaders, privateKeyBytes)
if err != nil {
return err
}
signedString = tmp
usedHeaders = tmp2
} else {
tmp, tmp2, err := CreateSignatureRSA(method, r.URL, mappedHeaders, privateKeyBytes)
if err != nil {
return err
}
signedString = tmp
usedHeaders = tmp2
}
signature := CreateSignatureHeaderContent(
keyId,
signedString,
usedHeaders...,
)
headers.Set("Signature", signature)
return nil
}
func NewRequest(method string, url string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, url, body)
if err != nil {
return nil, err
}
req.Header.Add(
"User-Agent",
"Linstrom v0.0.0-pre-alpha ("+config.GlobalConfig.General.GetFullDomain()+")",
)
req.Header.Add("Date", time.Now().UTC().Format(http.TimeFormat))
return req, nil
}