84 lines
1.9 KiB
Go
84 lines
1.9 KiB
Go
package signer
|
|
|
|
import (
|
|
"errors"
|
|
"net/http"
|
|
"os"
|
|
"time"
|
|
|
|
"git.makerforce.io/photos/photos/pkg/credentials"
|
|
"github.com/minio/minio-go/v6/pkg/signer"
|
|
)
|
|
|
|
type Signer struct {
|
|
expirations Expirations
|
|
}
|
|
|
|
type Expirations struct {
|
|
// Expiration time for list and read in time.Duration
|
|
Read time.Duration
|
|
// Expiration time for write in time.Duration
|
|
Write time.Duration
|
|
}
|
|
|
|
var ErrorExpirationTooLow = errors.New("expiration time too low")
|
|
|
|
func NewSigner(expirations Expirations) (*Signer, error) {
|
|
if expirations.Read == 0 {
|
|
expirations.Read = 30 * time.Minute
|
|
}
|
|
if expirations.Write == 0 {
|
|
expirations.Write = 5 * time.Minute
|
|
}
|
|
if expirations.Read < time.Second || expirations.Write < time.Second {
|
|
return nil, ErrorExpirationTooLow
|
|
}
|
|
return &Signer{
|
|
expirations: expirations,
|
|
}, nil
|
|
}
|
|
|
|
func NewSignerFromEnv() (*Signer, error) {
|
|
expirationRead, err := time.ParseDuration(os.Getenv("EXPIRATION_READ"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
expirationWrite, err := time.ParseDuration(os.Getenv("EXPIRATION_WRITE"))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
expirations := Expirations{Read: expirationRead, Write: expirationWrite}
|
|
return NewSigner(expirations)
|
|
}
|
|
|
|
func (s *Signer) PreSignRead(req *http.Request, cred credentials.Credential) *http.Request {
|
|
signedReq := signer.PreSignV4(
|
|
*req,
|
|
cred.AccessKey, cred.SecretKey, "",
|
|
cred.Region,
|
|
int64(s.expirations.Read/time.Second),
|
|
)
|
|
return signedReq
|
|
}
|
|
|
|
func (s *Signer) PreSignWrite(req *http.Request, cred credentials.Credential) *http.Request {
|
|
signedReq := signer.PreSignV4(
|
|
*req,
|
|
cred.AccessKey, cred.SecretKey, "",
|
|
cred.Region,
|
|
int64(s.expirations.Write/time.Second),
|
|
)
|
|
return signedReq
|
|
}
|
|
|
|
func (s *Signer) Sign(req *http.Request, cred credentials.Credential) *http.Request {
|
|
// All payloads unsigned
|
|
req.Header.Set("X-Amz-Content-Sha256", "UNSIGNED-PAYLOAD")
|
|
signedReq := signer.SignV4(
|
|
*req,
|
|
cred.AccessKey, cred.SecretKey, "",
|
|
cred.Region,
|
|
)
|
|
return signedReq
|
|
}
|