feat(cli): allow updates to runners' secrets

This commit allows the `forgejo-cli actions register` command to change
an existing runner's secret, as discussed in #4610.

It refactors `RegisterRunner` to extract the code that hashes the token,
moving this code to a method called `UpdateSecret` on `ActionRunner`.
A test for the method has been added.

The `RegisterRunner` function is updated so that:
- it relies on `ActionRunner.UpdateSecret` when creating new runners,
- it checks whether an existing runner's secret still matches the one
  passed on the command line,
- it updates the runner's secret if it wasn't created and it no longer
  matches.

A test has been added for the new behaviour.
This commit is contained in:
Emmanuel BENOÎT 2024-07-22 11:55:43 +02:00
parent fdb1874ada
commit 320ab7ed7f
No known key found for this signature in database
4 changed files with 88 additions and 12 deletions

View file

@ -6,10 +6,12 @@ package actions
import (
"context"
"encoding/binary"
"encoding/hex"
"fmt"
"strings"
"time"
auth_model "code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
repo_model "code.gitea.io/gitea/models/repo"
"code.gitea.io/gitea/models/shared/types"
@ -151,6 +153,22 @@ func (r *ActionRunner) GenerateToken() (err error) {
return err
}
// UpdateSecret updates the hash based on the specified token. It does not
// ensure that the runner's UUID matches the first 16 bytes of the token.
func (r *ActionRunner) UpdateSecret(token string) error {
saltBytes, err := util.CryptoRandomBytes(16)
if err != nil {
return fmt.Errorf("CryptoRandomBytes %v", err)
}
salt := hex.EncodeToString(saltBytes)
r.Token = token
r.TokenSalt = salt
r.TokenHash = auth_model.HashToken(token, salt)
return nil
}
func init() {
db.RegisterModel(&ActionRunner{})
}