chore: avoid log.Fatal() for jwtx/signingkey (#11066)

The module calling `log.Fatal()` (which terminates the process) prevents the calling function to enrich the error message with vital information allowing the user to track down problematic configuration directives. Also this was impeding unit tests.

One such case is where the path to the specified key can not be created, as demonstrated in the test case. Here the error message is:

```
Error while loading or creating JWT key: Error generating private key ...: mkdir ...: permission denied
```

`log.Fatal()` is kept for `f.Close()` errors which indicate much more severe but very rare underlying issues. Handling these would require broader changes.

Reviewed-on: https://codeberg.org/forgejo/forgejo/pulls/11066
Reviewed-by: Gusted <gusted@noreply.codeberg.org>
Co-authored-by: Nils Goroll <nils.goroll@uplex.de>
Co-committed-by: Nils Goroll <nils.goroll@uplex.de>
This commit is contained in:
Nils Goroll 2026-01-27 22:42:03 +01:00 committed by Gusted
parent c198082975
commit 5440aaea21
2 changed files with 8 additions and 3 deletions

View file

@ -291,7 +291,7 @@ func CreateSigningKey(algorithm string, key any) (SigningKey, error) {
func loadOrCreateAsymmetricKey(keyPath, algorithm string) (any, error) {
isExist, err := util.IsExist(keyPath)
if err != nil {
log.Fatal("Unable to check if %s exists. Error: %v", keyPath, err)
return nil, fmt.Errorf("Unable to check if %s exists. Error: %v", keyPath, err)
}
if !isExist {
err := func() error {
@ -352,8 +352,7 @@ func loadOrCreateAsymmetricKey(keyPath, algorithm string) (any, error) {
return pem.Encode(f, privateKeyPEM)
}()
if err != nil {
log.Fatal("Error generating private key: %v", err)
return nil, err
return nil, fmt.Errorf("Error generating private key %s: %v", keyPath, err)
}
}

View file

@ -111,3 +111,9 @@ func TestLoadOrCreateAsymmetricKey(t *testing.T) {
assert.NotNil(t, parsedKey.(ed25519.PrivateKey))
})
}
func TestCannotCreatePrivateKey(t *testing.T) {
_, err := InitAsymmetricSigningKey("/dev/directory-does-not-exist-and-you-should-not-have-permission-to-create/privatekey.pem", "RS256")
require.Error(t, err)
require.ErrorContains(t, err, "Error generating private key")
}