183 lines
6.3 KiB
Go
183 lines
6.3 KiB
Go
package api
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"strings"
|
|
"unicode"
|
|
"unicode/utf8"
|
|
|
|
"github.com/jackc/pgx/v5"
|
|
"otche/internal/store"
|
|
)
|
|
|
|
const apiKeyMetadata = `jsonb_build_object('id',id,'name',name,'prefix',prefix,'scopes',scopes,'created_at',created_at,'expires_at',expires_at,'last_used_at',last_used_at,'revoked_at',revoked_at)`
|
|
|
|
func validAPIKeyScope(scope string) bool {
|
|
switch scope {
|
|
case "profiles:read", "jobs:read", "jobs:write", "uploads:read", "uploads:write", "artifacts:read":
|
|
return true
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (s *Server) authenticateAPIKey(w http.ResponseWriter, r *http.Request, scope string) (identity, bool) {
|
|
reject := func() (identity, bool) {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="otche"`)
|
|
fail(w, http.StatusUnauthorized, "unauthenticated", "Invalid or expired API key")
|
|
return identity{}, false
|
|
}
|
|
values := r.Header.Values("Authorization")
|
|
if len(values) != 1 {
|
|
return reject()
|
|
}
|
|
parts := strings.Fields(values[0])
|
|
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") || len(parts[1]) != 70 || !strings.HasPrefix(parts[1], "otche_") {
|
|
return reject()
|
|
}
|
|
for _, c := range parts[1][6:] {
|
|
if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f') {
|
|
return reject()
|
|
}
|
|
}
|
|
a := identity{Role: "operator", RestrictedJobResponse: true} // Keys never inherit the session administrator's cross-owner bypass.
|
|
var id string
|
|
var scopes []string
|
|
err := s.db.QueryRow(r.Context(), `SELECT k.id::text,u.id::text,u.username,k.scopes FROM api_keys k JOIN users u ON u.id=k.owner_id WHERE k.token_hash=$1 AND k.revoked_at IS NULL AND k.expires_at>now() AND NOT u.disabled`, hashToken(parts[1])).Scan(&id, &a.ID, &a.Username, &scopes)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return reject()
|
|
}
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return identity{}, false
|
|
}
|
|
if scope == "" {
|
|
fail(w, http.StatusForbidden, "session_required", "This operation requires an interactive session")
|
|
return identity{}, false
|
|
}
|
|
permitted := false
|
|
for _, granted := range scopes {
|
|
if granted == "jobs:read" {
|
|
a.RestrictedJobResponse = false
|
|
}
|
|
if granted == scope {
|
|
permitted = true
|
|
}
|
|
}
|
|
if !permitted {
|
|
w.Header().Set("WWW-Authenticate", `Bearer realm="otche", error="insufficient_scope", scope="`+scope+`"`)
|
|
fail(w, http.StatusForbidden, "insufficient_scope", "API key lacks required scope: "+scope)
|
|
return identity{}, false
|
|
}
|
|
// Approximate successful authentication activity, without a write on every poll.
|
|
_, err = s.db.Exec(r.Context(), `UPDATE api_keys SET last_used_at=now() WHERE id=$1 AND (last_used_at IS NULL OR last_used_at<now()-interval '1 minute')`, id)
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return identity{}, false
|
|
}
|
|
return a, true
|
|
}
|
|
|
|
func (s *Server) apiKeyRoutes() {
|
|
s.mux.HandleFunc("GET /api/v1/api-keys", s.protected(false, s.apiKeys))
|
|
s.mux.HandleFunc("POST /api/v1/api-keys", s.protected(false, s.createAPIKey))
|
|
s.mux.HandleFunc("DELETE /api/v1/api-keys/{id}", s.protected(false, s.revokeAPIKey))
|
|
}
|
|
|
|
func (s *Server) apiKeys(w http.ResponseWriter, r *http.Request) {
|
|
s.list(w, r, `SELECT `+apiKeyMetadata+` FROM api_keys WHERE owner_id=$1 ORDER BY created_at DESC,id`, user(r).ID)
|
|
}
|
|
|
|
func (s *Server) createAPIKey(w http.ResponseWriter, r *http.Request) {
|
|
var in struct {
|
|
Name string `json:"name"`
|
|
Scopes []string `json:"scopes"`
|
|
ExpiresInDays int `json:"expires_in_days"`
|
|
}
|
|
if !decode(w, r, &in) {
|
|
return
|
|
}
|
|
in.Name = strings.TrimSpace(in.Name)
|
|
invalidName := !utf8.ValidString(in.Name) || utf8.RuneCountInString(in.Name) < 1 || utf8.RuneCountInString(in.Name) > 80
|
|
for _, c := range in.Name {
|
|
invalidName = invalidName || unicode.IsControl(c)
|
|
}
|
|
if invalidName || in.ExpiresInDays < 1 || in.ExpiresInDays > 365 || len(in.Scopes) == 0 || len(in.Scopes) > 6 {
|
|
fail(w, 400, "invalid_request", "Use a name of 1-80 characters, 1-365 expiry days and explicit scopes")
|
|
return
|
|
}
|
|
seen := make(map[string]bool, len(in.Scopes))
|
|
for _, scope := range in.Scopes {
|
|
if !validAPIKeyScope(scope) || seen[scope] {
|
|
fail(w, 400, "invalid_request", "Scopes must be known and unique")
|
|
return
|
|
}
|
|
seen[scope] = true
|
|
}
|
|
tx, err := s.db.Begin(r.Context())
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return
|
|
}
|
|
defer tx.Rollback(r.Context())
|
|
// Serialize issuance per owner so concurrent requests cannot exceed the cap.
|
|
var owner string
|
|
err = tx.QueryRow(r.Context(), `SELECT id::text FROM users WHERE id=$1 AND NOT disabled FOR UPDATE`, user(r).ID).Scan(&owner)
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return
|
|
}
|
|
// A reset may have revoked this session while issuance waited for the owner lock.
|
|
// This separate READ COMMITTED statement sees the reset's committed changes.
|
|
var liveSession bool
|
|
err = tx.QueryRow(r.Context(), `SELECT EXISTS(SELECT 1 FROM sessions WHERE token_hash=$1 AND user_id=$2 AND expires_at>now())`, user(r).TokenHash, owner).Scan(&liveSession)
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return
|
|
}
|
|
if !liveSession {
|
|
fail(w, 401, "unauthenticated", "Session expired")
|
|
return
|
|
}
|
|
var count int
|
|
err = tx.QueryRow(r.Context(), `SELECT count(*) FROM api_keys WHERE owner_id=$1 AND revoked_at IS NULL AND expires_at>now()`, owner).Scan(&count)
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return
|
|
}
|
|
if count >= 20 {
|
|
fail(w, 409, "key_limit", "At most 20 active API keys per account; revoke an unused key first")
|
|
return
|
|
}
|
|
token := "otche_" + randomToken()
|
|
var metadata []byte
|
|
err = tx.QueryRow(r.Context(), `INSERT INTO api_keys(id,owner_id,name,token_hash,prefix,scopes,expires_at) VALUES($1,$2,$3,$4,$5,$6,now()+$7*interval '1 day') RETURNING `+apiKeyMetadata,
|
|
store.NewID(), owner, in.Name, hashToken(token), token[:18], in.Scopes, in.ExpiresInDays).Scan(&metadata)
|
|
if err == nil {
|
|
err = tx.Commit(r.Context())
|
|
}
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return
|
|
}
|
|
// No secret in list, logs or URL; this is the only response containing it.
|
|
jsonResponse(w, 201, struct {
|
|
Key json.RawMessage `json:"key"`
|
|
Token string `json:"token"`
|
|
}{metadata, token})
|
|
}
|
|
|
|
func (s *Server) revokeAPIKey(w http.ResponseWriter, r *http.Request) {
|
|
tag, err := s.db.Exec(r.Context(), `UPDATE api_keys SET revoked_at=COALESCE(revoked_at,now()) WHERE id=$1::uuid AND owner_id=$2`, r.PathValue("id"), user(r).ID)
|
|
if err != nil {
|
|
s.dbError(w, err)
|
|
return
|
|
}
|
|
if tag.RowsAffected() == 0 {
|
|
fail(w, 404, "not_found", "Resource not found")
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|