fix(webui): a personal token create that fails is revoked and bounded under the dashboard timeout (#1717)
This commit is contained in:
1 file changed
+30
-2
@@ -1,7 +1,10 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -11,7 +14,12 @@ import (
|
||||
"github.com/samcharles93/archie-core/internal/domain/identity"
|
||||
)
|
||||
|
||||
const maxTokenNameLength = 40
|
||||
const (
|
||||
maxTokenNameLength = 40
|
||||
|
||||
// personalTokenBindTimeout is under the dashboard's own request timeout.
|
||||
personalTokenBindTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// Personal API tokens belong to the signed-in person; the State Store acts
|
||||
// on the principal the request carries, so these handlers name no one.
|
||||
@@ -50,7 +58,7 @@ func (a *identitiesAPI) handlePersonalTokenCreate(w http.ResponseWriter, r *http
|
||||
http.Error(w, "cannot create token", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if err := a.tokens.AddPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
|
||||
if err := a.addPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
|
||||
writeIdentityError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -59,6 +67,26 @@ func (a *identitiesAPI) handlePersonalTokenCreate(w http.ResponseWriter, r *http
|
||||
writeJSON(w, map[string]string{"id": subject.Subject, "token": raw})
|
||||
}
|
||||
|
||||
// addPersonalToken binds the token under its own deadline, shorter than the
|
||||
// dashboard's, so a slow State Store fails the request instead of outliving
|
||||
// the caller. The token is shown only once, so a bind that fails may still
|
||||
// have committed: revoke it, detached from the request that is over, rather
|
||||
// than leave a token nobody holds.
|
||||
func (a *identitiesAPI) addPersonalToken(ctx context.Context, subject identity.Subject, name string, expiresAt *time.Time) error {
|
||||
bindCtx, cancel := context.WithTimeout(ctx, personalTokenBindTimeout)
|
||||
defer cancel()
|
||||
err := a.tokens.AddPersonalToken(bindCtx, subject, name, expiresAt)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
revokeCtx, revokeCancel := context.WithTimeout(context.WithoutCancel(ctx), personalTokenBindTimeout)
|
||||
defer revokeCancel()
|
||||
if revokeErr := a.tokens.RevokePersonalToken(revokeCtx, subject.Subject); revokeErr != nil && !errors.Is(revokeErr, identity.ErrNotFound) {
|
||||
return errors.Join(err, fmt.Errorf("revoke unconfirmed token: %w", revokeErr))
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// decodeTokenRequest reads a token request's name and lifetime, the shape the
|
||||
// personal-token route and the per-identity token route share.
|
||||
func decodeTokenRequest(w http.ResponseWriter, r *http.Request) (string, *time.Time, bool) {
|
||||
|
||||
Reference in new issue
Block a user