Files
archie/internal/webui/personal_tokens.go
T

147 lines
4.6 KiB
Go

package webui
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
"unicode/utf8"
"github.com/samcharles93/archie-core/internal/domain/access"
"github.com/samcharles93/archie-core/internal/domain/identity"
)
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.
func (a *identitiesAPI) handlePersonalTokensList(w http.ResponseWriter, r *http.Request) {
if !personalTokenOwner(r) {
writeJSON(w, map[string]any{"tokens": []identity.PersonalToken{}, "available": false})
return
}
if !a.personalTokensReady(w, r) {
return
}
tokens, err := a.tokens.ListPersonalTokens(r.Context())
if err != nil {
writeIdentityError(w, err)
return
}
if tokens == nil {
tokens = []identity.PersonalToken{}
}
writeJSON(w, map[string]any{"tokens": tokens, "available": true})
}
// handlePersonalTokenCreate makes a token here and sends only its hash to the
// State Store; the response is the one time the token is shown.
func (a *identitiesAPI) handlePersonalTokenCreate(w http.ResponseWriter, r *http.Request) {
if !a.personalTokensReady(w, r) {
return
}
name, expiresAt, ok := decodeTokenRequest(w, r)
if !ok {
return
}
raw, subject, err := identity.NewPersonalToken()
if err != nil {
http.Error(w, "cannot create token", http.StatusInternalServerError)
return
}
if err := a.addPersonalToken(r.Context(), subject, name, expiresAt); err != nil {
writeIdentityError(w, err)
return
}
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusCreated)
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) {
var body struct {
Name string `json:"name"`
Days int `json:"days"`
}
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4<<10)).Decode(&body); err != nil {
http.Error(w, "invalid request", http.StatusBadRequest)
return "", nil, false
}
name := strings.TrimSpace(body.Name)
if name == "" || utf8.RuneCountInString(name) > maxTokenNameLength {
http.Error(w, "Name a token in up to 40 characters.", http.StatusBadRequest)
return "", nil, false
}
var expiresAt *time.Time
switch body.Days {
case 0:
case 7, 30, 90:
t := time.Now().UTC().AddDate(0, 0, body.Days)
expiresAt = &t
default:
http.Error(w, "Lifetime is 7, 30 or 90 days, or none.", http.StatusBadRequest)
return "", nil, false
}
return name, expiresAt, true
}
func (a *identitiesAPI) handlePersonalTokenRevoke(w http.ResponseWriter, r *http.Request) {
if !a.personalTokensReady(w, r) {
return
}
if err := a.tokens.RevokePersonalToken(r.Context(), r.PathValue("id")); err != nil {
writeIdentityError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func personalTokenOwner(r *http.Request) bool {
p, ok := access.PrincipalFromContext(r.Context())
return ok && p.IdentityID != "" && p.IdentityID != identity.SystemID
}
func (a *identitiesAPI) personalTokensReady(w http.ResponseWriter, r *http.Request) bool {
if !personalTokenOwner(r) {
http.Error(w, "Personal tokens need a signed-in person.", http.StatusForbidden)
return false
}
if a.tokens == nil {
http.Error(w, "personal tokens unavailable", http.StatusServiceUnavailable)
return false
}
return true
}