snapshot of https://github.com/ory/kratos.git (master, 2026-09-15; blobs > 131072B omitted)
Some checks failed
CI / Run tests and lints (push) Failing after 29s
CI / Build CLI docs (push) Has been skipped
CI / Run Playwright end-to-end tests (mysql) (push) Failing after 3s
CI / Run Playwright end-to-end tests (postgres) (push) Failing after 2s
CI / Run Playwright end-to-end tests (sqlite) (push) Failing after 3s
CodeQL / Analyze (go) (push) Failing after 4s
CodeQL / Analyze (javascript) (push) Failing after 3s
Docker Image Scanners / scanners (push) Failing after 4s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Run end-to-end tests (postgres) (push) Failing after 19s
CI / Run end-to-end tests (sqlite) (push) Failing after 2s
CI / Run Playwright end-to-end tests (cockroach) (push) Failing after 2s
CI / Draft newsletter (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped
Some checks failed
CI / Run tests and lints (push) Failing after 29s
CI / Build CLI docs (push) Has been skipped
CI / Run Playwright end-to-end tests (mysql) (push) Failing after 3s
CI / Run Playwright end-to-end tests (postgres) (push) Failing after 2s
CI / Run Playwright end-to-end tests (sqlite) (push) Failing after 3s
CodeQL / Analyze (go) (push) Failing after 4s
CodeQL / Analyze (javascript) (push) Failing after 3s
Docker Image Scanners / scanners (push) Failing after 4s
Synchronize Issue Labels / Synchronize Issue Labels (push) Has been skipped
CI / Run end-to-end tests (postgres) (push) Failing after 19s
CI / Run end-to-end tests (sqlite) (push) Failing after 2s
CI / Run Playwright end-to-end tests (cockroach) (push) Failing after 2s
CI / Draft newsletter (push) Has been skipped
CI / Generate release (push) Has been skipped
CI / Pending approval Slack notification (push) Has been skipped
CI / Send newsletter (push) Has been skipped
This commit is contained in:
332
cmd/hashers/argon2/calibrate.go
Normal file
332
cmd/hashers/argon2/calibrate.go
Normal file
@@ -0,0 +1,332 @@
|
||||
// Copyright © 2023 Ory Corp
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package argon2
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/ory/x/configx"
|
||||
|
||||
"github.com/ory/x/cmdx"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/inhies/go-bytesize"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/ory/kratos/driver/config"
|
||||
"github.com/ory/kratos/hash"
|
||||
)
|
||||
|
||||
const (
|
||||
FlagStartMemory = "start-memory"
|
||||
FlagMaxMemory = "max-memory"
|
||||
FlagAdjustMemory = "adjust-memory-by"
|
||||
FlagStartIterations = "start-iterations"
|
||||
FlagMaxConcurrent = "max-concurrent"
|
||||
|
||||
FlagRuns = "probe-runs"
|
||||
)
|
||||
|
||||
type (
|
||||
colorWriter struct {
|
||||
c *color.Color
|
||||
w io.Writer
|
||||
}
|
||||
loadResult struct {
|
||||
r *resultTable
|
||||
v *config.Argon2
|
||||
}
|
||||
loadResults []*loadResult
|
||||
)
|
||||
|
||||
var _ cmdx.Table = loadResults{}
|
||||
|
||||
func (l loadResults) Header() []string {
|
||||
return append((&resultTable{}).Header(), "MEMOry PARAM", "ITERATIONS PARAM")
|
||||
}
|
||||
|
||||
func (l loadResults) Table() [][]string {
|
||||
t := make([][]string, len(l))
|
||||
|
||||
for i, r := range l {
|
||||
t[i] = append(r.r.Columns(), fmt.Sprintf("%d", r.v.Memory), fmt.Sprintf("%d", r.v.Iterations))
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
|
||||
func (l loadResults) Interface() interface{} {
|
||||
return l
|
||||
}
|
||||
|
||||
func (l loadResults) Len() int {
|
||||
return len(l)
|
||||
}
|
||||
|
||||
func (c *colorWriter) Write(o []byte) (int, error) {
|
||||
return c.c.Fprintf(c.w, "%s", o)
|
||||
}
|
||||
|
||||
func newCalibrateCmd() *cobra.Command {
|
||||
var (
|
||||
maxMemory, adjustMemory bytesize.ByteSize = 0, 512 * bytesize.MB
|
||||
runs int
|
||||
)
|
||||
|
||||
flagConfig := &argon2Config{
|
||||
localConfig: config.Argon2{},
|
||||
}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "calibrate <requests-per-minute>",
|
||||
Args: cobra.ExactArgs(1),
|
||||
Short: "Computes Optimal Argon2 Parameters",
|
||||
Long: `This command helps you calibrate the configuration parameters for Argon2. Password hashing is a trade-off between security, resource consumption, and user experience. Resource consumption should not be too high and the login should not take too long.
|
||||
|
||||
We recommend that the login process takes between half a second and one second for password hashing, giving a good balance between security and user experience.
|
||||
|
||||
Please note that the values depend on the machine you run the hashing on. If you have RAM constraints, please set the memory dedicated to Ory Kratos to avoid out of memory panics.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
progressPrinter := cmdx.NewLoudErrPrinter(cmd)
|
||||
resultPrinter := cmdx.NewLoudPrinter(cmd, &colorWriter{c: color.New(color.FgGreen), w: cmd.ErrOrStderr()})
|
||||
|
||||
conf, err := configProvider(cmd, flagConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// always take start flags, or their default
|
||||
conf.localConfig.Memory = flagConfig.localConfig.Memory
|
||||
conf.localConfig.Iterations = flagConfig.localConfig.Iterations
|
||||
|
||||
desiredDuration := conf.localConfig.ExpectedDuration
|
||||
|
||||
reqPerMin, err := strconv.ParseInt(args[0], 0, 0)
|
||||
if err != nil {
|
||||
// we want the error and usage string printed so just return
|
||||
return err
|
||||
}
|
||||
|
||||
hasher := hash.NewHasherArgon2(conf)
|
||||
|
||||
var currentDuration time.Duration
|
||||
|
||||
_, _ = progressPrinter.Printf("Increasing memory to get over %s:\n", desiredDuration)
|
||||
|
||||
for {
|
||||
if maxMemory != 0 && conf.localConfig.Memory > maxMemory {
|
||||
// don't further increase memory
|
||||
_, _ = progressPrinter.Println(" ouch, hit the memory limit there")
|
||||
conf.localConfig.Memory = maxMemory
|
||||
break
|
||||
}
|
||||
|
||||
currentDuration, err = probe(cmd, hasher, runs, progressPrinter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf(" took %s with %s of memory\n", currentDuration, conf.localConfig.Memory)
|
||||
|
||||
if currentDuration > desiredDuration {
|
||||
if conf.localConfig.Memory <= adjustMemory {
|
||||
// adjusting the memory would now result in <= 0B
|
||||
adjustMemory = adjustMemory >> 1
|
||||
}
|
||||
conf.localConfig.Memory -= adjustMemory
|
||||
break
|
||||
}
|
||||
|
||||
// adjust config
|
||||
conf.localConfig.Memory += adjustMemory
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf("Decreasing memory to get under %s:\n", desiredDuration)
|
||||
|
||||
for {
|
||||
currentDuration, err = probe(cmd, hasher, runs, progressPrinter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf(" took %s with %s of memory\n", currentDuration, conf.localConfig.Memory)
|
||||
|
||||
if currentDuration < desiredDuration {
|
||||
break
|
||||
}
|
||||
|
||||
for conf.localConfig.Memory <= adjustMemory {
|
||||
// adjusting the memory would now result in <= 0B
|
||||
adjustMemory = adjustMemory >> 1
|
||||
}
|
||||
|
||||
// adjust config
|
||||
conf.localConfig.Memory -= adjustMemory
|
||||
}
|
||||
|
||||
_, _ = resultPrinter.Printf("Settled on %s of memory.\n", conf.localConfig.Memory)
|
||||
_, _ = progressPrinter.Printf("Increasing iterations to get over %s:\n", desiredDuration)
|
||||
|
||||
for {
|
||||
currentDuration, err = probe(cmd, hasher, runs, progressPrinter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf(" took %s with %d iterations\n", currentDuration, conf.localConfig.Iterations)
|
||||
|
||||
if currentDuration > desiredDuration {
|
||||
if conf.localConfig.Iterations > 1 {
|
||||
conf.localConfig.Iterations -= 1
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
// adjust config
|
||||
conf.localConfig.Iterations += 1
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf("Decreasing iterations to get under %s:\n", desiredDuration)
|
||||
|
||||
for {
|
||||
currentDuration, err = probe(cmd, hasher, runs, progressPrinter)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf(" took %s with %d iterations\n", currentDuration, conf.localConfig.Iterations)
|
||||
|
||||
// break also when iterations is 1; this catches the case where 1 was only slightly under the desired time and took longer a bit longer on another run
|
||||
if currentDuration < desiredDuration || conf.localConfig.Iterations == 1 {
|
||||
break
|
||||
}
|
||||
|
||||
// adjust config
|
||||
conf.localConfig.Iterations -= 1
|
||||
}
|
||||
_, _ = resultPrinter.Printf("Settled on %d iterations.\n", conf.localConfig.Iterations)
|
||||
|
||||
results := make(loadResults, 5)
|
||||
for i := 0; i < len(results); i++ {
|
||||
_, _ = progressPrinter.Printf("\nRunning load test to simulate %d login requests per minute.\n", reqPerMin)
|
||||
|
||||
res, err := runLoadTest(cmd, conf, int(reqPerMin))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cv, _ := conf.HasherArgon2()
|
||||
ccv := *cv
|
||||
results[i] = &loadResult{r: res, v: &ccv}
|
||||
|
||||
_, _ = progressPrinter.Println("The load test result is:")
|
||||
_, _ = progressPrinter.Println()
|
||||
cmdx.PrintRow(cmd, res)
|
||||
|
||||
switch {
|
||||
// too fast
|
||||
case res.MedianTime < conf.localConfig.ExpectedDuration:
|
||||
_, _ = progressPrinter.Printf("The median was %s under the minimal duration of %s, going to increase the hash cost.\n", conf.localConfig.ExpectedDuration-res.MedianTime, conf.localConfig.ExpectedDuration)
|
||||
|
||||
// try to increase memory first
|
||||
if res.MaxMem+64*bytesize.MB < maxMemory {
|
||||
// only small amounts of memory are sensible as we already benchmarked a single, non-concurrent request
|
||||
conf.localConfig.Memory += 64 * bytesize.MB
|
||||
_, _ = progressPrinter.Printf("Increasing memory to %s\n", conf.localConfig.Memory)
|
||||
} else {
|
||||
// increasing memory is not allowed by maxMemory, therefore increase CPU load
|
||||
conf.localConfig.Iterations++
|
||||
_, _ = progressPrinter.Printf("Increasing iterations to %d\n", conf.localConfig.Iterations)
|
||||
}
|
||||
// too much memory
|
||||
case res.MaxMem > conf.localConfig.DedicatedMemory:
|
||||
_, _ = progressPrinter.Printf("The required memory was %s more than the maximum allowed of %s.\n", res.MaxMem-maxMemory, conf.localConfig.DedicatedMemory)
|
||||
|
||||
//nolint:gosec // disable G115
|
||||
conf.localConfig.Memory -= (res.MaxMem - conf.localConfig.DedicatedMemory) / bytesize.ByteSize(reqPerMin)
|
||||
_, _ = progressPrinter.Printf("Decreasing memory to %s\n", conf.localConfig.Memory)
|
||||
// too slow
|
||||
case res.MaxTime > conf.localConfig.ExpectedDeviation+conf.localConfig.ExpectedDuration:
|
||||
_, _ = progressPrinter.Printf("The longest request took %s longer than the longest acceptable time of %s, going to decrease the hash cost.\n", res.MaxTime-conf.localConfig.ExpectedDeviation+conf.localConfig.ExpectedDuration, conf.localConfig.ExpectedDeviation+conf.localConfig.ExpectedDuration)
|
||||
|
||||
// try to decrease iterations first
|
||||
if conf.localConfig.Iterations > 1 {
|
||||
conf.localConfig.Iterations--
|
||||
_, _ = progressPrinter.Printf("Decreasing iterations to %d\n", conf.localConfig.Iterations)
|
||||
} else {
|
||||
// decreasing iterations is not possible anymore, decreasing memory
|
||||
// only small amounts of memory are sensible as we already benchmarked a single, non-concurrent request
|
||||
conf.localConfig.Memory -= 64 * bytesize.MB
|
||||
_, _ = progressPrinter.Printf("Decreasing memory to %s\n", conf.localConfig.Memory)
|
||||
}
|
||||
// too high deviation
|
||||
case res.StdDev > conf.localConfig.ExpectedDeviation:
|
||||
_, _ = progressPrinter.Printf("The deviation was %s more than the expected deviation of %s.\n", res.StdDev-conf.localConfig.ExpectedDeviation, conf.localConfig.ExpectedDeviation)
|
||||
|
||||
// try to decrease iterations first
|
||||
if conf.localConfig.Iterations > 1 {
|
||||
conf.localConfig.Iterations--
|
||||
_, _ = progressPrinter.Printf("Decreasing iterations to %d\n", conf.localConfig.Iterations)
|
||||
} else {
|
||||
// decreasing iterations is not possible anymore, decreasing memory
|
||||
// only small amounts of memory are sensible as we already benchmarked a single, non-concurrent request
|
||||
conf.localConfig.Memory -= 64 * bytesize.MB
|
||||
_, _ = progressPrinter.Printf("Decreasing memory to %s\n", conf.localConfig.Memory)
|
||||
}
|
||||
// all values seem reasonable
|
||||
default:
|
||||
_, _ = progressPrinter.Println("These values look good to me.")
|
||||
_, _ = progressPrinter.Println()
|
||||
cmdx.PrintRow(cmd, conf)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), "Could not automatically determine good parameters. Have a look at all the measurements taken and select acceptable values yourself. Have a look in the docs for more information: https://www.ory.com/kratos/docs/debug/performance-out-of-memory-password-hashing-argon2")
|
||||
cmdx.PrintTable(cmd, results)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
flags := cmd.Flags()
|
||||
|
||||
flags.IntVarP(&runs, FlagRuns, "r", 2, "Runs per probe, median of all runs is taken as the result.")
|
||||
|
||||
flags.VarP(&flagConfig.localConfig.Memory, FlagStartMemory, "m", "Amount of memory to start probing at.")
|
||||
flags.Var(&maxMemory, FlagMaxMemory, "Maximum memory allowed (0 means no limit).")
|
||||
flags.Var(&adjustMemory, FlagAdjustMemory, "Amount by which the memory is adjusted in every step while probing.")
|
||||
|
||||
flags.Uint32VarP(&flagConfig.localConfig.Iterations, FlagStartIterations, "i", 1, "Number of iterations to start probing at.")
|
||||
|
||||
flags.Uint8(FlagMaxConcurrent, 16, "Maximum number of concurrent hashing operations.")
|
||||
|
||||
registerArgon2ConstantConfigFlags(flags, flagConfig)
|
||||
cmdx.RegisterFormatFlags(flags)
|
||||
configx.RegisterFlags(flags)
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func probe(cmd *cobra.Command, hasher hash.Hasher, runs int, progressPrinter *cmdx.ConditionalPrinter) (time.Duration, error) {
|
||||
// force GC at the start of the experiment
|
||||
runtime.GC()
|
||||
|
||||
start := time.Now()
|
||||
|
||||
var mid time.Time
|
||||
for i := 0; i < runs; i++ {
|
||||
mid = time.Now()
|
||||
_, err := hasher.Generate(cmd.Context(), []byte("password"))
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not generate a hash: %s\n", err)
|
||||
return 0, cmdx.FailSilently(cmd)
|
||||
}
|
||||
|
||||
_, _ = progressPrinter.Printf(" took %s in try %d\n", time.Since(mid), i)
|
||||
}
|
||||
return time.Duration(int64(time.Since(start)) / int64(runs)), nil
|
||||
}
|
||||
83
cmd/hashers/argon2/hash.go
Normal file
83
cmd/hashers/argon2/hash.go
Normal file
@@ -0,0 +1,83 @@
|
||||
// Copyright © 2023 Ory Corp
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package argon2
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/ory/kratos/hash"
|
||||
"github.com/ory/x/cmdx"
|
||||
"github.com/ory/x/configx"
|
||||
"github.com/ory/x/flagx"
|
||||
)
|
||||
|
||||
const (
|
||||
FlagParallel = "parallel"
|
||||
)
|
||||
|
||||
func newHashCmd() *cobra.Command {
|
||||
flagConfig := &argon2Config{}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "hash <password1> [<password2> ...]",
|
||||
Short: "Hash a list of passwords for benchmarking the hashing parameters",
|
||||
Args: cobra.MinimumNArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
conf, err := configProvider(cmd, flagConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
flagConfig.ctx = cmd.Context()
|
||||
|
||||
hasher := hash.NewHasherArgon2(conf)
|
||||
hashes := make([][]byte, len(args))
|
||||
errs := make(chan error, len(args))
|
||||
|
||||
start := time.Now()
|
||||
|
||||
for i, pw := range args {
|
||||
go func(i int, pw string) {
|
||||
start := time.Now()
|
||||
h, err := hasher.Generate(cmd.Context(), []byte(pw))
|
||||
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "password %d: %s\n", i, time.Since(start))
|
||||
|
||||
hashes[i] = h
|
||||
errs <- err
|
||||
}(i, pw)
|
||||
|
||||
if !flagx.MustGetBool(cmd, FlagParallel) {
|
||||
if err := <-errs; err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not generate hash: %s\n", err.Error())
|
||||
return cmdx.FailSilently(cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if flagx.MustGetBool(cmd, FlagParallel) {
|
||||
for i := 0; i < len(args); i++ {
|
||||
if err := <-errs; err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Could not generate hash: %s\n", err.Error())
|
||||
return cmdx.FailSilently(cmd)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "total: %s\n", time.Since(start))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
flags := cmd.Flags()
|
||||
|
||||
flags.Bool(FlagParallel, false, "Run all hashing operations in parallel.")
|
||||
|
||||
registerArgon2ConfigFlags(flags, flagConfig)
|
||||
configx.RegisterFlags(flags)
|
||||
|
||||
return cmd
|
||||
}
|
||||
269
cmd/hashers/argon2/loadtest.go
Normal file
269
cmd/hashers/argon2/loadtest.go
Normal file
@@ -0,0 +1,269 @@
|
||||
// Copyright © 2023 Ory Corp
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package argon2
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/ory/x/flagx"
|
||||
|
||||
"github.com/fatih/color"
|
||||
"github.com/inhies/go-bytesize"
|
||||
"github.com/montanaflynn/stats"
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/sync/errgroup"
|
||||
|
||||
"github.com/ory/kratos/hash"
|
||||
"github.com/ory/x/cmdx"
|
||||
"github.com/ory/x/configx"
|
||||
)
|
||||
|
||||
type resultTable struct {
|
||||
TotalTime time.Duration `json:"total_time"`
|
||||
MedianTime time.Duration `json:"median_request_time"`
|
||||
StdDev time.Duration `json:"std_deviation"`
|
||||
MinTime time.Duration `json:"min_request_time"`
|
||||
MaxTime time.Duration `json:"max_request_time"`
|
||||
MaxMem bytesize.ByteSize `json:"mem_used"`
|
||||
}
|
||||
|
||||
var (
|
||||
ErrSampleTimeExceeded = fmt.Errorf("the sample time was exceeded")
|
||||
ErrMemoryConsumptionExceeded = fmt.Errorf("the memory consumption was exceeded")
|
||||
|
||||
_ cmdx.TableRow = &resultTable{}
|
||||
)
|
||||
|
||||
func (r *resultTable) Header() []string {
|
||||
return []string{"TOTAL SAMPLE TIME", "MEDIAN REQUEST TIME", "STANDARD DEVIATION", "MIN REQUEST TIME", "MAX REQUEST TIME", "MEMOry USED"}
|
||||
}
|
||||
|
||||
func (r *resultTable) Columns() []string {
|
||||
return []string{
|
||||
r.TotalTime.String(),
|
||||
r.MedianTime.String(),
|
||||
r.StdDev.String(),
|
||||
r.MinTime.String(),
|
||||
r.MaxTime.String(),
|
||||
r.MaxMem.String(),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *resultTable) Interface() interface{} {
|
||||
return r
|
||||
}
|
||||
|
||||
func newLoadTestCmd() *cobra.Command {
|
||||
flagConf := &argon2Config{}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "load-test <authentication-requests-per-minute>",
|
||||
Short: "Simulate the password hashing with a number of concurrent requests/minute.",
|
||||
Long: "Simulates a number of concurrent authentication requests per minute. Gives statistical data about the measured performance and resource consumption. Can be used to tune and test the hashing parameters for peak demand situations.",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
perMinute, err := strconv.ParseInt(args[0], 0, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
flagConf.ctx = cmd.Context()
|
||||
|
||||
conf, err := configProvider(cmd, flagConf)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !flagx.MustGetBool(cmd, cmdx.FlagQuiet) {
|
||||
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), "The hashing configuration used is:")
|
||||
cmdx.PrintRow(cmd, conf)
|
||||
}
|
||||
|
||||
res, err := runLoadTest(cmd, conf, int(perMinute))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cmdx.PrintRow(cmd, res)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
|
||||
registerArgon2ConfigFlags(cmd.Flags(), flagConf)
|
||||
configx.RegisterFlags(cmd.Flags())
|
||||
cmdx.RegisterFormatFlags(cmd.Flags())
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runLoadTest(cmd *cobra.Command, conf *argon2Config, reqPerMin int) (*resultTable, error) {
|
||||
// force GC at the start of the experiment
|
||||
runtime.GC()
|
||||
|
||||
sampleTime := time.Minute / 3
|
||||
reqNum := reqPerMin / int(time.Minute/sampleTime)
|
||||
|
||||
progressPrinter := cmdx.NewLoudErrPrinter(cmd)
|
||||
_, _ = progressPrinter.Printf("It takes about %s to collect all necessary data, please be patient.\n", sampleTime)
|
||||
|
||||
ctx, cancel := context.WithCancel(cmd.Context())
|
||||
hasher := hash.NewHasherArgon2(conf)
|
||||
allDone := make(chan struct{})
|
||||
startAll := time.Now()
|
||||
var cancelReason error
|
||||
|
||||
var memStats []uint64
|
||||
go func() {
|
||||
clock := time.NewTicker(time.Second)
|
||||
defer func() {
|
||||
clock.Stop()
|
||||
}()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-cmd.Context().Done():
|
||||
return
|
||||
case <-allDone:
|
||||
return
|
||||
case <-clock.C:
|
||||
// cancel if the allowed time is exceeded by 110%
|
||||
if time.Since(startAll) > ((sampleTime+conf.localConfig.ExpectedDuration+conf.localConfig.ExpectedDeviation)/100)*110 {
|
||||
cancelReason = ErrSampleTimeExceeded
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
|
||||
ms := runtime.MemStats{}
|
||||
runtime.ReadMemStats(&ms)
|
||||
|
||||
// cancel if memory is exceeded by 110%
|
||||
if ms.HeapAlloc > (uint64(conf.localConfig.DedicatedMemory)/100)*110 {
|
||||
cancelReason = ErrMemoryConsumptionExceeded
|
||||
cancel()
|
||||
return
|
||||
}
|
||||
|
||||
memStats = append(memStats, ms.HeapAlloc)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
// don't read std_in when quiet
|
||||
if flagx.MustGetBool(cmd, cmdx.FlagQuiet) {
|
||||
return
|
||||
}
|
||||
|
||||
input := make([]byte, 1)
|
||||
for {
|
||||
n, err := cmd.InOrStdin().Read(input)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if n != 0 {
|
||||
_, _ = color.New(color.FgRed).Fprintln(cmd.ErrOrStderr(), "I SAID BE PATIENT!!!")
|
||||
return
|
||||
}
|
||||
|
||||
select {
|
||||
case <-allDone:
|
||||
return
|
||||
case <-cmd.Context().Done():
|
||||
return
|
||||
case <-time.After(time.Millisecond):
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
calcTimes := make([]time.Duration, reqNum)
|
||||
eg, _ := errgroup.WithContext(ctx)
|
||||
|
||||
for i := 0; i < reqNum; i++ {
|
||||
eg.Go(func(i int) func() error {
|
||||
return func() error {
|
||||
// wait randomly before starting, max. sample time
|
||||
//#nosec G404 -- just a timeout to collect statistical data
|
||||
t := time.Duration(rand.Intn(int(sampleTime)))
|
||||
timer := time.NewTimer(t)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-timer.C:
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
done := make(chan struct{})
|
||||
var err error
|
||||
|
||||
go func() {
|
||||
_, err = hasher.Generate(ctx, []byte("password"))
|
||||
close(done)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
case <-done:
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
calcTimes[i] = time.Since(start)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
}(i))
|
||||
}
|
||||
|
||||
if err := eg.Wait(); err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Error during hashing: %+v\n", err)
|
||||
return nil, cmdx.FailSilently(cmd)
|
||||
}
|
||||
switch cancelReason {
|
||||
case ErrSampleTimeExceeded:
|
||||
memUsed, err2 := stats.LoadRawData(memStats).Max()
|
||||
if err2 != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Unexpected maths error: %+v\nRaw Data: %+v\n", cancelReason, memStats)
|
||||
}
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "The hashing load test took too long. This indicates that you don't have enough resources to handle %d login requests per minute with the desired minimal time of %s. The memory used was %s. Either dedicate more CPU/memory, or decrease the hashing cost (memory and iterations parameters).\n", reqPerMin, conf.localConfig.ExpectedDuration, bytesize.ByteSize(memUsed))
|
||||
return nil, cmdx.FailSilently(cmd)
|
||||
case ErrMemoryConsumptionExceeded:
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "The hashing load test exceeded the memory limit of %s. This indicates that you don't have enough resources to handle %d login requests per minute with the desired minimal time of %s. Either dedicate more memory, or decrease the hashing cost (memory and iterations parameters).\n", conf.localConfig.DedicatedMemory, reqPerMin, conf.localConfig.ExpectedDuration)
|
||||
return nil, cmdx.FailSilently(cmd)
|
||||
}
|
||||
|
||||
totalTime := time.Since(startAll)
|
||||
close(allDone)
|
||||
|
||||
calcData := stats.LoadRawData(calcTimes)
|
||||
|
||||
duration := func(f func() (float64, error)) time.Duration {
|
||||
v, err := f()
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Unexpected maths error: %+v\nRaw Data: %+v\n", err, calcTimes)
|
||||
}
|
||||
return time.Duration(int64(v))
|
||||
}
|
||||
|
||||
memUsed, err := stats.LoadRawData(memStats).Max()
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Unexpected maths error: %+v\nRaw Data: %+v\n", err, memStats)
|
||||
}
|
||||
|
||||
return &resultTable{
|
||||
TotalTime: totalTime,
|
||||
MedianTime: duration(calcData.Mean),
|
||||
StdDev: duration(calcData.StandardDeviation),
|
||||
MinTime: duration(calcData.Min),
|
||||
MaxTime: duration(calcData.Max),
|
||||
MaxMem: bytesize.ByteSize(memUsed),
|
||||
}, nil
|
||||
}
|
||||
177
cmd/hashers/argon2/root.go
Normal file
177
cmd/hashers/argon2/root.go
Normal file
@@ -0,0 +1,177 @@
|
||||
// Copyright © 2023 Ory Corp
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package argon2
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
|
||||
"github.com/ory/x/contextx"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/ory/kratos/driver/config"
|
||||
"github.com/ory/x/cmdx"
|
||||
"github.com/ory/x/configx"
|
||||
"github.com/ory/x/logrusx"
|
||||
)
|
||||
|
||||
const (
|
||||
FlagIterations = "iterations"
|
||||
FlagParallelism = "parallelism"
|
||||
FlagSaltLength = "salt-length"
|
||||
FlagKeyLength = "key-length"
|
||||
FlagMemory = "memory"
|
||||
FlagDedicatedMemory = "dedicated-memory"
|
||||
FlagMinimalDuration = "min-duration"
|
||||
FlagExpectedDeviation = "expected-deviation"
|
||||
)
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "argon2",
|
||||
}
|
||||
|
||||
func RegisterCommandRecursive(parent *cobra.Command) {
|
||||
parent.AddCommand(rootCmd)
|
||||
|
||||
rootCmd.AddCommand(newCalibrateCmd(), newHashCmd(), newLoadTestCmd())
|
||||
}
|
||||
|
||||
func registerArgon2ConstantConfigFlags(flags *pflag.FlagSet, c *argon2Config) {
|
||||
// set default value first
|
||||
c.localConfig.DedicatedMemory = config.Argon2DefaultDedicatedMemory
|
||||
flags.Var(&c.localConfig.DedicatedMemory, FlagDedicatedMemory, "Amount of memory dedicated for password hashing. Kratos will try to not consume more memory.")
|
||||
flags.DurationVar(&c.localConfig.ExpectedDuration, FlagMinimalDuration, config.Argon2DefaultDuration, "Minimal duration a hashing operation (~login request) takes.")
|
||||
flags.DurationVar(&c.localConfig.ExpectedDeviation, FlagExpectedDeviation, config.Argon2DefaultDeviation, "Expected deviation of the time a hashing operation (~login request) takes.")
|
||||
|
||||
flags.Uint8Var(&c.localConfig.Parallelism, FlagParallelism, config.Argon2DefaultParallelism, "Number of threads to use.")
|
||||
|
||||
flags.Uint32Var(&c.localConfig.SaltLength, FlagSaltLength, config.Argon2DefaultSaltLength, "Length of the salt in bytes.")
|
||||
flags.Uint32Var(&c.localConfig.KeyLength, FlagKeyLength, config.Argon2DefaultKeyLength, "Length of the key in bytes.")
|
||||
}
|
||||
|
||||
func registerArgon2ConfigFlags(flags *pflag.FlagSet, c *argon2Config) {
|
||||
flags.Uint32Var(&c.localConfig.Iterations, FlagIterations, 1, "Number of iterations to start probing at.")
|
||||
|
||||
// set default value first
|
||||
c.localConfig.Memory = config.Argon2DefaultMemory
|
||||
flags.Var(&c.localConfig.Memory, FlagMemory, "Memory to use.")
|
||||
|
||||
registerArgon2ConstantConfigFlags(flags, c)
|
||||
}
|
||||
|
||||
func configProvider(cmd *cobra.Command, flagConf *argon2Config) (*argon2Config, error) {
|
||||
l := logrusx.New("Ory Kratos", config.Version)
|
||||
conf := &argon2Config{}
|
||||
var err error
|
||||
conf.config, err = config.New(
|
||||
cmd.Context(),
|
||||
l,
|
||||
cmd.ErrOrStderr(),
|
||||
&contextx.Default{},
|
||||
configx.WithFlags(cmd.Flags()),
|
||||
configx.SkipValidation(),
|
||||
configx.WithContext(cmd.Context()),
|
||||
configx.WithImmutables("hashers"),
|
||||
)
|
||||
if err != nil {
|
||||
_, _ = fmt.Fprintf(cmd.ErrOrStderr(), "Unable to initialize the config provider: %s\n", err)
|
||||
return nil, cmdx.FailSilently(cmd)
|
||||
}
|
||||
conf.localConfig = *conf.config.HasherArgon2(cmd.Context())
|
||||
|
||||
if cmd.Flags().Changed(FlagIterations) {
|
||||
conf.localConfig.Iterations = flagConf.localConfig.Iterations
|
||||
}
|
||||
if cmd.Flags().Changed(FlagParallelism) {
|
||||
conf.localConfig.Parallelism = flagConf.localConfig.Parallelism
|
||||
}
|
||||
if cmd.Flags().Changed(FlagMemory) {
|
||||
conf.localConfig.Memory = flagConf.localConfig.Memory
|
||||
}
|
||||
if cmd.Flags().Changed(FlagDedicatedMemory) {
|
||||
conf.localConfig.DedicatedMemory = flagConf.localConfig.DedicatedMemory
|
||||
}
|
||||
if cmd.Flags().Changed(FlagKeyLength) {
|
||||
conf.localConfig.KeyLength = flagConf.localConfig.KeyLength
|
||||
}
|
||||
if cmd.Flags().Changed(FlagSaltLength) {
|
||||
conf.localConfig.SaltLength = flagConf.localConfig.SaltLength
|
||||
}
|
||||
if cmd.Flags().Changed(FlagExpectedDeviation) {
|
||||
conf.localConfig.ExpectedDeviation = flagConf.localConfig.ExpectedDeviation
|
||||
}
|
||||
if cmd.Flags().Changed(FlagMinimalDuration) {
|
||||
conf.localConfig.ExpectedDuration = flagConf.localConfig.ExpectedDuration
|
||||
}
|
||||
|
||||
return conf, nil
|
||||
}
|
||||
|
||||
type (
|
||||
argon2Config struct {
|
||||
localConfig config.Argon2
|
||||
config *config.Config
|
||||
ctx context.Context
|
||||
}
|
||||
)
|
||||
|
||||
var _ cmdx.TableRow = (*argon2Config)(nil)
|
||||
|
||||
func (c *argon2Config) Header() []string {
|
||||
var header []string
|
||||
|
||||
t := reflect.TypeOf(c.localConfig)
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
header = append(header, strings.ReplaceAll(strings.ToUpper(t.Field(i).Tag.Get("json")), "_", " "))
|
||||
}
|
||||
|
||||
return header
|
||||
}
|
||||
|
||||
func (c *argon2Config) Columns() []string {
|
||||
conf, _ := c.HasherArgon2()
|
||||
return []string{
|
||||
conf.Memory.String(),
|
||||
fmt.Sprintf("%d", conf.Iterations),
|
||||
fmt.Sprintf("%d", conf.Parallelism),
|
||||
fmt.Sprintf("%d", conf.SaltLength),
|
||||
fmt.Sprintf("%d", conf.KeyLength),
|
||||
conf.ExpectedDuration.String(),
|
||||
conf.ExpectedDeviation.String(),
|
||||
conf.DedicatedMemory.String(),
|
||||
}
|
||||
}
|
||||
|
||||
func (c *argon2Config) Interface() interface{} {
|
||||
i, _ := c.HasherArgon2()
|
||||
return i
|
||||
}
|
||||
|
||||
func (c *argon2Config) Config() *config.Config {
|
||||
ac, _ := c.HasherArgon2()
|
||||
for k, v := range map[string]interface{}{
|
||||
config.ViperKeyHasherArgon2ConfigIterations: ac.Iterations,
|
||||
config.ViperKeyHasherArgon2ConfigMemory: ac.Memory,
|
||||
config.ViperKeyHasherArgon2ConfigParallelism: ac.Parallelism,
|
||||
config.ViperKeyHasherArgon2ConfigDedicatedMemory: ac.DedicatedMemory,
|
||||
config.ViperKeyHasherArgon2ConfigKeyLength: ac.KeyLength,
|
||||
config.ViperKeyHasherArgon2ConfigSaltLength: ac.SaltLength,
|
||||
config.ViperKeyHasherArgon2ConfigExpectedDuration: ac.ExpectedDuration,
|
||||
config.ViperKeyHasherArgon2ConfigExpectedDeviation: ac.ExpectedDeviation,
|
||||
} {
|
||||
_ = c.config.Set(c.ctx, k, v)
|
||||
}
|
||||
return c.config
|
||||
}
|
||||
|
||||
func (c *argon2Config) HasherArgon2() (*config.Argon2, error) {
|
||||
if c.localConfig.Memory == 0 {
|
||||
c.localConfig.Memory = config.Argon2DefaultMemory
|
||||
}
|
||||
return &c.localConfig, nil
|
||||
}
|
||||
25
cmd/hashers/root.go
Normal file
25
cmd/hashers/root.go
Normal file
@@ -0,0 +1,25 @@
|
||||
// Copyright © 2023 Ory Corp
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
|
||||
package hashers
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/ory/kratos/cmd/hashers/argon2"
|
||||
)
|
||||
|
||||
func NewRootCmd() *cobra.Command {
|
||||
c := &cobra.Command{
|
||||
Use: "hashers",
|
||||
Short: "This command contains helpers around hashing",
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func RegisterCommandRecursive(parent *cobra.Command) {
|
||||
rootCmd := NewRootCmd()
|
||||
parent.AddCommand(rootCmd)
|
||||
|
||||
argon2.RegisterCommandRecursive(rootCmd)
|
||||
}
|
||||
Reference in New Issue
Block a user