Add scoped personal API keys, OpenAPI documentation and security regressions
This commit is contained in:
1 parent
9bb6ed29ac
commit
87a501f507
12 files changed
+5319
-18
No files matched your search
@@ -126,6 +126,9 @@ func (s *Server) updateUser(w http.ResponseWriter, r *http.Request) {
|
||||
if e == nil {
|
||||
_, e = tx.Exec(r.Context(), `DELETE FROM sessions WHERE user_id=$1`, id)
|
||||
}
|
||||
if e == nil && (in.Password != nil || in.Disabled != nil && *in.Disabled) {
|
||||
_, e = tx.Exec(r.Context(), `UPDATE api_keys SET revoked_at=now() WHERE owner_id=$1 AND revoked_at IS NULL`, id)
|
||||
}
|
||||
if e != nil {
|
||||
s.dbError(w, e)
|
||||
return
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
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"} // 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 == scope {
|
||||
permitted = true
|
||||
break
|
||||
}
|
||||
}
|
||||
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
|
||||
}
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"otche/internal/store"
|
||||
)
|
||||
|
||||
// Real PostgreSQL and the actual HTTP router: credentials must not expand authority.
|
||||
func TestAPIKeySecurityBoundary(t *testing.T) {
|
||||
url := os.Getenv("OTCHE_TEST_DATABASE_URL")
|
||||
if url == "" {
|
||||
t.Skip("OTCHE_TEST_DATABASE_URL required for isolated PostgreSQL regression")
|
||||
}
|
||||
ctx := context.Background()
|
||||
admin, err := pgxpool.New(ctx, url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer admin.Close()
|
||||
schema := "test_" + strings.ReplaceAll(store.NewID(), "-", "")
|
||||
if _, err = admin.Exec(ctx, "CREATE SCHEMA "+schema); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer admin.Exec(ctx, "DROP SCHEMA "+schema+" CASCADE")
|
||||
cfg, err := pgxpool.ParseConfig(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = schema
|
||||
db, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer db.Close()
|
||||
if err = store.Migrate(ctx, db); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := New(db, Config{Origin: "https://localhost", ArtifactRoot: t.TempDir()})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
exec := func(q string, args ...any) {
|
||||
t.Helper()
|
||||
if _, err := db.Exec(ctx, q, args...); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
type session struct{ id, token, csrf string }
|
||||
makeUser := func(name, role string) session {
|
||||
t.Helper()
|
||||
v := session{store.NewID(), randomToken(), randomToken()}
|
||||
exec(`INSERT INTO users(id,username,password_hash,role) VALUES($1,$2,'unused',$3)`, v.id, name, role)
|
||||
exec(`INSERT INTO sessions(token_hash,user_id,csrf_token,expires_at) VALUES($1,$2,$3,now()+interval '1 hour')`, hashToken(v.token), v.id, v.csrf)
|
||||
return v
|
||||
}
|
||||
owner := makeUser("key-admin", "admin")
|
||||
other := makeUser("other-owner", "operator")
|
||||
request := func(method, path, body string, ss *session, authorization *string, csrf bool) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, "/api/v1"+path, strings.NewReader(body))
|
||||
if ss != nil {
|
||||
r.AddCookie(&http.Cookie{Name: "otche_session", Value: ss.token})
|
||||
if csrf {
|
||||
r.Header.Set("Origin", "https://localhost")
|
||||
r.Header.Set("X-CSRF-Token", ss.csrf)
|
||||
}
|
||||
}
|
||||
if authorization != nil {
|
||||
r.Header.Set("Authorization", *authorization)
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
expect := func(w *httptest.ResponseRecorder, status int) {
|
||||
t.Helper()
|
||||
if w.Code != status {
|
||||
t.Fatalf("expected HTTP %d got %d: %s", status, w.Code, w.Body)
|
||||
}
|
||||
}
|
||||
type credential struct {
|
||||
Key struct{ ID, Prefix string }
|
||||
Token string
|
||||
}
|
||||
issue := func(ss session, scopes []string) credential {
|
||||
t.Helper()
|
||||
body, _ := json.Marshal(map[string]any{"name": "CI key", "expires_in_days": 90, "scopes": scopes})
|
||||
w := request("POST", "/api-keys", string(body), &ss, nil, true)
|
||||
expect(w, 201)
|
||||
var c credential
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &c); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return c
|
||||
}
|
||||
allScopes := []string{"profiles:read", "jobs:read", "jobs:write", "uploads:read", "uploads:write", "artifacts:read"}
|
||||
key := issue(owner, allScopes)
|
||||
bearer := "Bearer " + key.Token
|
||||
if len(key.Token) != 70 || !strings.HasPrefix(key.Token, "otche_") {
|
||||
t.Fatal("malformed issued credential")
|
||||
}
|
||||
var stored string
|
||||
if err = db.QueryRow(ctx, `SELECT token_hash FROM api_keys WHERE id=$1`, key.Key.ID).Scan(&stored); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if stored != hashToken(key.Token) || strings.Contains(stored, key.Token) {
|
||||
t.Fatal("credential not stored as digest")
|
||||
}
|
||||
listed := request("GET", "/api-keys", "", &owner, nil, false)
|
||||
expect(listed, 200)
|
||||
if strings.Contains(listed.Body.String(), key.Token) || strings.Contains(listed.Body.String(), stored) || strings.Contains(listed.Body.String(), "token_hash") {
|
||||
t.Fatal("credential leaked from list")
|
||||
}
|
||||
expect(request("GET", "/profiles", "", nil, &bearer, false), 200)
|
||||
expect(request("HEAD", "/profiles", "", nil, &bearer, false), 200)
|
||||
var used *time.Time
|
||||
if err = db.QueryRow(ctx, `SELECT last_used_at FROM api_keys WHERE id=$1`, key.Key.ID).Scan(&used); err != nil || used == nil {
|
||||
t.Fatal("successful authentication not recorded", err)
|
||||
}
|
||||
// Invalid explicit credentials never downgrade to an otherwise valid browser session.
|
||||
for _, invalid := range []string{"", "Basic abc", "Bearer otche_bad", "Bearer " + strings.Repeat("0", 64)} {
|
||||
expect(request("GET", "/profiles", "", &owner, &invalid, false), 401)
|
||||
}
|
||||
unknown := "Bearer otche_" + strings.Repeat("0", 64)
|
||||
expect(request("GET", "/profiles", "", &owner, &unknown, false), 401)
|
||||
duplicate := httptest.NewRequest("GET", "/api/v1/profiles", nil)
|
||||
duplicate.Header.Add("Authorization", bearer)
|
||||
duplicate.Header.Add("Authorization", bearer)
|
||||
duplicateResponse := httptest.NewRecorder()
|
||||
s.ServeHTTP(duplicateResponse, duplicate)
|
||||
expect(duplicateResponse, 401)
|
||||
expect(request("GET", "/profiles?api_key="+key.Token, "", nil, nil, false), 401)
|
||||
for _, path := range []string{"/api-keys", "/auth/session", "/admin/users"} {
|
||||
expect(request("GET", path, "", &owner, &bearer, false), 403)
|
||||
}
|
||||
expect(request("POST", "/auth/login", `{}`, nil, &bearer, false), 403)
|
||||
expect(request("POST", "/auth/logout", `{}`, &owner, &bearer, true), 403)
|
||||
expect(request("POST", "/api-keys", `{}`, &owner, nil, false), 403)
|
||||
for _, origin := range []string{"https://localhost", "https://foreign.invalid"} {
|
||||
r := httptest.NewRequest("DELETE", "/api/v1/api-keys/"+key.Key.ID, nil)
|
||||
r.AddCookie(&http.Cookie{Name: "otche_session", Value: owner.token})
|
||||
r.Header.Set("Origin", origin)
|
||||
r.Header.Set("X-CSRF-Token", "wrong")
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
expect(w, 403)
|
||||
}
|
||||
expect(request("DELETE", "/api-keys/"+key.Key.ID, "", &other, nil, true), 404)
|
||||
readOnly := issue(owner, []string{"profiles:read"})
|
||||
readBearer := "Bearer " + readOnly.Token
|
||||
expect(request("GET", "/jobs", "", nil, &readBearer, false), 403)
|
||||
expect(request("POST", "/uploads", "", nil, &readBearer, false), 403)
|
||||
expect(request("POST", "/jobs", `{}`, nil, &readBearer, false), 403)
|
||||
expect(request("POST", "/api-keys", `{}`, nil, &readBearer, false), 403)
|
||||
writeOnly := issue(owner, []string{"jobs:write"})
|
||||
writeBearer := "Bearer " + writeOnly.Token
|
||||
expect(request("GET", "/jobs", "", nil, &writeBearer, false), 403)
|
||||
// A scoped write reaches normal validation without cookie Origin/CSRF.
|
||||
expect(request("POST", "/jobs", `{}`, nil, &writeBearer, false), 400)
|
||||
missingID := store.NewID()
|
||||
for _, granted := range allScopes {
|
||||
limited := issue(owner, []string{granted})
|
||||
authorization := "Bearer " + limited.Token
|
||||
for _, endpoint := range []struct {
|
||||
method, path, scope string
|
||||
status int
|
||||
}{
|
||||
{"GET", "/profiles", "profiles:read", 200},
|
||||
{"GET", "/dashboard", "jobs:read", 200},
|
||||
{"GET", "/jobs", "jobs:read", 200},
|
||||
{"GET", "/jobs/" + missingID, "jobs:read", 404},
|
||||
{"GET", "/jobs/" + missingID + "/events", "jobs:read", 404},
|
||||
{"POST", "/jobs", "jobs:write", 400},
|
||||
{"POST", "/jobs/" + missingID + "/cancel", "jobs:write", 404},
|
||||
{"POST", "/jobs/" + missingID + "/retry", "jobs:write", 404},
|
||||
{"POST", "/uploads", "uploads:write", 400},
|
||||
{"GET", "/uploads/" + missingID + "/content", "uploads:read", 404},
|
||||
{"GET", "/jobs/" + missingID + "/artifacts", "artifacts:read", 404},
|
||||
{"GET", "/artifacts/" + missingID + "/content", "artifacts:read", 404},
|
||||
{"GET", "/attempts/" + missingID + "/video", "artifacts:read", 404},
|
||||
} {
|
||||
want := 403
|
||||
if endpoint.scope == granted {
|
||||
want = endpoint.status
|
||||
}
|
||||
t.Run(granted+"/"+endpoint.method+endpoint.path, func(t *testing.T) {
|
||||
w := request(endpoint.method, endpoint.path, `{}`, nil, &authorization, false)
|
||||
if w.Code != want {
|
||||
t.Fatalf("scope boundary: expected%d got%d %s", want, w.Code, w.Body)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
for _, body := range []string{
|
||||
`{"name":"bad","expires_in_days":0,"scopes":["jobs:read"]}`,
|
||||
`{"name":"bad","expires_in_days":366,"scopes":["jobs:read"]}`,
|
||||
`{"name":"bad","expires_in_days":1,"scopes":[]}`,
|
||||
`{"name":"bad","expires_in_days":1,"scopes":["admin"]}`,
|
||||
`{"name":"bad","expires_in_days":1,"scopes":["jobs:read","jobs:read"]}`,
|
||||
`{"name":"bad\u0000","expires_in_days":1,"scopes":["jobs:read"]}`,
|
||||
} {
|
||||
expect(request("POST", "/api-keys", body, &owner, nil, true), 400)
|
||||
}
|
||||
// Seed two owners' completed observations, including private downloadable artifacts.
|
||||
makeJob := func(ss session) (string, string, string, string) {
|
||||
upload, job, run, attempt, profile, revision, artifact := store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID(), store.NewID()
|
||||
exec(`INSERT INTO uploads(id,owner_id,filename,size,sha256,storage_key) VALUES($1::uuid,$2,'sample.exe',4,'digest',$1::uuid::text)`, upload, ss.id)
|
||||
exec(`INSERT INTO jobs(id,owner_id,upload_id,execution_filename,settings,status) VALUES($1,$2,$3,'sample.exe','{}','finished')`, job, ss.id, upload)
|
||||
exec(`INSERT INTO profiles(id,name,os,architecture) VALUES($1,'Windows test','windows','x64')`, profile)
|
||||
exec(`INSERT INTO revisions(id,profile_id,source_ref,fingerprint,config_digest) VALUES($1,$2,'source','fingerprint','digest')`, revision, profile)
|
||||
exec(`INSERT INTO runs(id,job_id,profile_id,revision_id,profile_name,status) VALUES($1,$2,$3,$4,'Windows test','finished')`, run, job, profile, revision)
|
||||
exec(`INSERT INTO attempts(id,run_id,command_id,phase) VALUES($1,$2,$3,'finished')`, attempt, run, store.NewID())
|
||||
exec(`INSERT INTO artifacts(id,job_id,attempt_id,kind,filename,content_type,size,sha256,storage_key) VALUES($1::uuid,$2,$3,'report','report.json','application/json',4,'digest',$1::uuid::text)`, artifact, job, attempt)
|
||||
if err := os.WriteFile(s.cfg.ArtifactRoot+"/"+upload, []byte("data"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(s.cfg.ArtifactRoot+"/"+artifact, []byte("data"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return job, upload, artifact, attempt
|
||||
}
|
||||
ownJob, ownUpload, ownArtifact, _ := makeJob(owner)
|
||||
foreignJob, foreignUpload, foreignArtifact, foreignAttempt := makeJob(other)
|
||||
for _, path := range []string{"/jobs/" + ownJob, "/uploads/" + ownUpload + "/content", "/artifacts/" + ownArtifact + "/content"} {
|
||||
expect(request("GET", path, "", nil, &bearer, false), 200)
|
||||
}
|
||||
for _, path := range []string{"/jobs/" + foreignJob, "/jobs/" + foreignJob + "/events", "/jobs/" + foreignJob + "/artifacts", "/uploads/" + foreignUpload + "/content", "/artifacts/" + foreignArtifact + "/content", "/attempts/" + foreignAttempt + "/video"} {
|
||||
expect(request("GET", path, "", nil, &bearer, false), 404)
|
||||
}
|
||||
for _, suffix := range []string{"/cancel", "/retry"} {
|
||||
expect(request("POST", "/jobs/"+foreignJob+suffix, `{}`, nil, &bearer, false), 404)
|
||||
}
|
||||
list := request("GET", "/jobs", "", nil, &bearer, false)
|
||||
expect(list, 200)
|
||||
if !strings.Contains(list.Body.String(), ownJob) || strings.Contains(list.Body.String(), foreignJob) {
|
||||
t.Fatal("admin-owned key escaped owner isolation")
|
||||
}
|
||||
// Browser administrator access remains unchanged.
|
||||
expect(request("GET", "/jobs/"+foreignJob, "", &owner, nil, false), 200)
|
||||
// Exercise the automation protocol through the real handlers, not fixture echoes.
|
||||
uploadRequest := httptest.NewRequest("POST", "/api/v1/uploads", strings.NewReader("harmless integration fixture"))
|
||||
uploadRequest.Header.Set("Authorization", bearer)
|
||||
uploadRequest.Header.Set("X-Filename", "integration.exe")
|
||||
uploadResponse := httptest.NewRecorder()
|
||||
s.ServeHTTP(uploadResponse, uploadRequest)
|
||||
expect(uploadResponse, 201)
|
||||
var uploaded struct{ ID, SHA256 string }
|
||||
if err := json.Unmarshal(uploadResponse.Body.Bytes(), &uploaded); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if uploaded.SHA256 != hashToken("harmless integration fixture") {
|
||||
t.Fatal("upload digest mismatch")
|
||||
}
|
||||
downloaded := request("GET", "/uploads/"+uploaded.ID+"/content", "", nil, &bearer, false)
|
||||
expect(downloaded, 200)
|
||||
if downloaded.Body.String() != "harmless integration fixture" {
|
||||
t.Fatal("uploaded content changed")
|
||||
}
|
||||
var profileID string
|
||||
if err := db.QueryRow(ctx, `SELECT profile_id::text FROM runs WHERE job_id=$1`, ownJob).Scan(&profileID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := `{"internet":"offline","duration_seconds":30,"filename":"original","privilege":"user","args_mode":"none","args":[],"set_zoneid":false}`
|
||||
jobInput := fmt.Sprintf(`{"upload_id":%q,"profile_ids":[%q],"settings":%s}`, uploaded.ID, profileID, settings)
|
||||
expect(request("POST", "/jobs", jobInput, nil, &bearer, false), 409)
|
||||
exec(`INSERT INTO bindings(owner_id,pool,iso_storage,disk_storage,node,configured,isolation_expires_at) VALUES($1,'test','test','test','test',true,now()+interval '1 hour')`, owner.id)
|
||||
exec(`INSERT INTO heartbeats(name,seen_at,ready) VALUES('worker',now(),true)`)
|
||||
// Credentials do not bypass qualification, even for administrator-owned keys.
|
||||
expect(request("POST", "/jobs", jobInput, nil, &bearer, false), 409)
|
||||
exec(`UPDATE profiles SET enabled=true,state='published',qualification='qualified',current_revision_id=(SELECT id FROM revisions WHERE profile_id=$1) WHERE id=$1`, profileID)
|
||||
createdJob := request("POST", "/jobs", jobInput, nil, &bearer, false)
|
||||
expect(createdJob, 201)
|
||||
var admitted struct {
|
||||
ID string
|
||||
CancelRequested bool `json:"cancel_requested"`
|
||||
Runs []struct {
|
||||
ProfileName string `json:"profile_name"`
|
||||
Attempts []struct{ ID string }
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(createdJob.Body.Bytes(), &admitted); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(admitted.Runs) != 1 || admitted.Runs[0].ProfileName != "Windows test" || len(admitted.Runs[0].Attempts) != 1 {
|
||||
t.Fatal("admission did not snapshot selected source")
|
||||
}
|
||||
for _, path := range []string{"/dashboard", "/jobs/" + admitted.ID + "/events", "/jobs/" + admitted.ID + "/artifacts", "/attempts/" + admitted.Runs[0].Attempts[0].ID + "/video"} {
|
||||
expect(request("GET", path, "", nil, &bearer, false), 200)
|
||||
}
|
||||
expect(request("POST", "/jobs/"+admitted.ID+"/retry", `{}`, nil, &bearer, false), 409)
|
||||
canceled := request("POST", "/jobs/"+admitted.ID+"/cancel", `{}`, nil, &bearer, false)
|
||||
expect(canceled, 200)
|
||||
if err := json.Unmarshal(canceled.Body.Bytes(), &admitted); err != nil || !admitted.CancelRequested {
|
||||
t.Fatal("cancel not observable", err)
|
||||
}
|
||||
exec(`UPDATE attempts SET phase='finished' WHERE run_id IN(SELECT id FROM runs WHERE job_id=$1)`, admitted.ID)
|
||||
exec(`UPDATE jobs SET status='finished' WHERE id=$1`, admitted.ID)
|
||||
retried := request("POST", "/jobs/"+admitted.ID+"/retry", `{}`, nil, &bearer, false)
|
||||
expect(retried, 200)
|
||||
if err := json.Unmarshal(retried.Body.Bytes(), &admitted); err != nil || admitted.CancelRequested || len(admitted.Runs[0].Attempts) != 2 {
|
||||
t.Fatal("retry did not create a fresh attempt", err)
|
||||
}
|
||||
// A newly expired isolation proof closes admission for keys too.
|
||||
exec(`UPDATE bindings SET isolation_expires_at=now()-interval '1 second' WHERE owner_id=$1`, owner.id)
|
||||
expect(request("POST", "/jobs", jobInput, nil, &bearer, false), 409)
|
||||
expect(request("DELETE", "/api-keys/"+key.Key.ID, "", &owner, nil, true), 204)
|
||||
expect(request("DELETE", "/api-keys/"+key.Key.ID, "", &owner, nil, true), 204)
|
||||
expect(request("GET", "/profiles", "", nil, &bearer, false), 401)
|
||||
exec(`UPDATE api_keys SET created_at=now()-interval '2 days',expires_at=now()-interval '1 day' WHERE id=$1`, readOnly.Key.ID)
|
||||
expect(request("GET", "/profiles", "", nil, &readBearer, false), 401)
|
||||
// Disabling and then reenabling via the real admin API cannot resurrect keys.
|
||||
otherKey := issue(other, []string{"profiles:read"})
|
||||
otherBearer := "Bearer " + otherKey.Token
|
||||
expect(request("PATCH", "/admin/users/"+other.id, `{"disabled":true}`, &owner, nil, true), 200)
|
||||
expect(request("GET", "/profiles", "", nil, &otherBearer, false), 401)
|
||||
expect(request("PATCH", "/admin/users/"+other.id, `{"disabled":false}`, &owner, nil, true), 200)
|
||||
expect(request("GET", "/profiles", "", nil, &otherBearer, false), 401)
|
||||
// Reestablish a session after the admin mutation to issue a replacement.
|
||||
exec(`INSERT INTO sessions(token_hash,user_id,csrf_token,expires_at) VALUES($1,$2,$3,now()+interval '1 hour')`, hashToken(other.token), other.id, other.csrf)
|
||||
replacement := issue(other, []string{"profiles:read"})
|
||||
replacementBearer := "Bearer " + replacement.Token
|
||||
expect(request("PATCH", "/admin/users/"+other.id, `{"password":"New-regression-only-password"}`, &owner, nil, true), 200)
|
||||
expect(request("GET", "/profiles", "", nil, &replacementBearer, false), 401)
|
||||
// Concurrent issuance shares the owner lock, not a racy count-then-insert.
|
||||
capped := makeUser("concurrent-owner", "operator")
|
||||
statuses := make(chan int, 24)
|
||||
var wg sync.WaitGroup
|
||||
for range 24 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
statuses <- request("POST", "/api-keys", `{"name":"parallel","expires_in_days":1,"scopes":["profiles:read"]}`, &capped, nil, true).Code
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(statuses)
|
||||
created, limited := 0, 0
|
||||
for status := range statuses {
|
||||
switch status {
|
||||
case 201:
|
||||
created++
|
||||
case 409:
|
||||
limited++
|
||||
default:
|
||||
t.Fatalf("unexpected concurrent issue status %d", status)
|
||||
}
|
||||
}
|
||||
if created != 20 || limited != 4 {
|
||||
t.Fatalf("cap race: created=%d limited=%d", created, limited)
|
||||
}
|
||||
var cappedID string
|
||||
if err := db.QueryRow(ctx, `SELECT id::text FROM api_keys WHERE owner_id=$1 LIMIT 1`, capped.id).Scan(&cappedID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expect(request("DELETE", "/api-keys/"+cappedID, "", &capped, nil, true), 204)
|
||||
issue(capped, []string{"profiles:read"})
|
||||
db.Close()
|
||||
expect(request("GET", "/profiles", "", nil, &writeBearer, false), 500)
|
||||
fmt.Println("API keys: scopes, owner isolation, expiry/revocation, credential precedence, session CSRF, account resets, concurrent cap and database failure verified")
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
//go:embed openapi.json
|
||||
var openAPIDocument []byte
|
||||
|
||||
func (s *Server) documentationRoutes() {
|
||||
s.mux.HandleFunc("GET /api/v1/openapi.json", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
_, _ = w.Write(openAPIDocument)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Exercise the public HTTP surface, without database/session availability.
|
||||
func servedOpenAPI(t *testing.T) map[string]any {
|
||||
t.Helper()
|
||||
s := &Server{mux: http.NewServeMux()}
|
||||
s.documentationRoutes()
|
||||
r := httptest.NewRequest(http.MethodGet, "/api/v1/openapi.json", nil)
|
||||
r.Header.Set("Authorization", "Bearer deliberately-invalid")
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatalf("public OpenAPI status = %d: %s", w.Code, w.Body.String())
|
||||
}
|
||||
if ct := w.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||
t.Fatalf("OpenAPI Content-Type = %q", ct)
|
||||
}
|
||||
var document map[string]any
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &document); err != nil {
|
||||
t.Fatalf("decode served OpenAPI: %v", err)
|
||||
}
|
||||
return document
|
||||
}
|
||||
|
||||
func documentObject(t *testing.T, root map[string]any, path ...string) map[string]any {
|
||||
t.Helper()
|
||||
value := root
|
||||
for _, name := range path {
|
||||
next, ok := value[name].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("missing object %s at %s", name, strings.Join(path, "."))
|
||||
}
|
||||
value = next
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
func TestOpenAPIPublicDocumentAndMethods(t *testing.T) {
|
||||
document := servedOpenAPI(t)
|
||||
if document["openapi"] != "3.1.0" {
|
||||
t.Fatalf("unsupported OpenAPI dialect: %v", document["openapi"])
|
||||
}
|
||||
s := &Server{mux: http.NewServeMux()}
|
||||
s.documentationRoutes()
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead, http.MethodPost, http.MethodDelete} {
|
||||
w := httptest.NewRecorder()
|
||||
s.ServeHTTP(w, httptest.NewRequest(method, "/api/v1/openapi.json", nil))
|
||||
want := http.StatusMethodNotAllowed
|
||||
if method == http.MethodGet || method == http.MethodHead {
|
||||
want = http.StatusOK
|
||||
}
|
||||
if w.Code != want {
|
||||
t.Errorf("%s document: status %d, want %d", method, w.Code, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAPIAuthorizationContract(t *testing.T) {
|
||||
document := servedOpenAPI(t)
|
||||
paths := documentObject(t, document, "paths")
|
||||
expected := map[string]string{
|
||||
"get /profiles": "profiles:read",
|
||||
"get /dashboard": "jobs:read",
|
||||
"get /jobs": "jobs:read",
|
||||
"get /jobs/{id}": "jobs:read",
|
||||
"get /jobs/{id}/events": "jobs:read",
|
||||
"post /jobs": "jobs:write",
|
||||
"post /jobs/{id}/cancel": "jobs:write",
|
||||
"post /jobs/{id}/retry": "jobs:write",
|
||||
"post /uploads": "uploads:write",
|
||||
"get /uploads/{id}/content": "uploads:read",
|
||||
"get /jobs/{id}/artifacts": "artifacts:read",
|
||||
"get /artifacts/{id}/content": "artifacts:read",
|
||||
"get /attempts/{id}/video": "artifacts:read",
|
||||
}
|
||||
seenScopes := map[string]bool{}
|
||||
for route, scope := range expected {
|
||||
parts := strings.SplitN(route, " ", 2)
|
||||
op := documentObject(t, paths, parts[1], parts[0])
|
||||
if op["x-required-scope"] != scope {
|
||||
t.Errorf("%s scope = %v, want %s", route, op["x-required-scope"], scope)
|
||||
}
|
||||
seenScopes[scope] = true
|
||||
security, ok := op["security"].([]any)
|
||||
if !ok || len(security) != 2 {
|
||||
t.Fatalf("%s needs bearer OR cookie alternatives", route)
|
||||
}
|
||||
bearer, ok := security[0].(map[string]any)
|
||||
if !ok || !reflect.DeepEqual(bearer["BearerAuth"], []any{}) {
|
||||
t.Fatalf("%s HTTP bearer must not declare OAuth scopes", route)
|
||||
}
|
||||
cookie, ok := security[1].(map[string]any)
|
||||
if !ok || !reflect.DeepEqual(cookie["CookieSession"], []any{}) {
|
||||
t.Fatalf("%s missing cookie alternative", route)
|
||||
}
|
||||
_, csrf := cookie["CSRFToken"]
|
||||
if csrf != (parts[0] == "post") {
|
||||
t.Errorf("%s cookie CSRF requirement = %v", route, csrf)
|
||||
}
|
||||
}
|
||||
if len(seenScopes) != 6 {
|
||||
t.Fatalf("documented independent scopes = %d", len(seenScopes))
|
||||
}
|
||||
for _, route := range []string{"get /api-keys", "post /api-keys", "delete /api-keys/{id}", "get /auth/session", "post /auth/logout", "post /auth/login"} {
|
||||
parts := strings.SplitN(route, " ", 2)
|
||||
op := documentObject(t, paths, parts[1], parts[0])
|
||||
if op["x-session-only"] != true || op["x-required-scope"] != nil {
|
||||
t.Errorf("%s must not advertise API-key access", route)
|
||||
}
|
||||
for _, requirement := range op["security"].([]any) {
|
||||
if _, bearer := requirement.(map[string]any)["BearerAuth"]; bearer {
|
||||
t.Errorf("%s advertises forbidden bearer access", route)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/health", "/openapi.json"} {
|
||||
op := documentObject(t, paths, path, "get")
|
||||
if !reflect.DeepEqual(op["security"], []any{}) {
|
||||
t.Errorf("%s must be public", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAPIConsumerShapes(t *testing.T) {
|
||||
document := servedOpenAPI(t)
|
||||
schemas := documentObject(t, document, "components", "schemas")
|
||||
for _, tc := range []struct {
|
||||
schema string
|
||||
field string
|
||||
values []any
|
||||
}{
|
||||
{"SettingsInput", "duration_seconds", []any{float64(30), float64(60), float64(90), float64(120), float64(180), float64(300), float64(600), float64(900), float64(1200)}},
|
||||
{"SettingsInput", "internet", []any{"offline", "online"}},
|
||||
{"Attempt", "findings", []any{"unknown", "detected", "not_observed"}},
|
||||
{"Attempt", "telemetry", []any{"pending", "complete", "partial", "unavailable"}},
|
||||
{"Attempt", "cleanup", []any{"pending", "complete", "evidence_held", "failed"}},
|
||||
} {
|
||||
field := documentObject(t, schemas, tc.schema, "properties", tc.field)
|
||||
if !reflect.DeepEqual(field["enum"], tc.values) {
|
||||
t.Errorf("%s.%s enum = %v, want %v", tc.schema, tc.field, field["enum"], tc.values)
|
||||
}
|
||||
}
|
||||
for schema, fields := range map[string][]string{
|
||||
"JobInput": {"upload_id", "profile_ids", "settings"},
|
||||
"APIKeyInput": {"name", "scopes", "expires_in_days"},
|
||||
"APIKeyCreated": {"key", "token"},
|
||||
"JobPage": {"items", "total", "page", "page_size", "next_page"},
|
||||
} {
|
||||
decl := documentObject(t, schemas, schema)
|
||||
required, ok := decl["required"].([]any)
|
||||
if !ok {
|
||||
t.Fatalf("%s required fields missing", schema)
|
||||
}
|
||||
for _, field := range fields {
|
||||
found := false
|
||||
for _, item := range required {
|
||||
found = found || item == field
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("%s.%s must be required for consumers", schema, field)
|
||||
}
|
||||
}
|
||||
}
|
||||
for schema, fields := range map[string][]string{
|
||||
"APIKey": {"last_used_at", "revoked_at"},
|
||||
"Attempt": {"report", "allocation", "claimed_at", "started_at", "finished_at", "deadline_at"},
|
||||
"Job": {"queue_ahead"},
|
||||
"JobPage": {"next_page"},
|
||||
"Event": {"attempt_id"},
|
||||
} {
|
||||
for _, field := range fields {
|
||||
decl := documentObject(t, schemas, schema, "properties", field)
|
||||
variants, ok := decl["anyOf"].([]any)
|
||||
nullable := false
|
||||
if ok {
|
||||
for _, variant := range variants {
|
||||
nullable = nullable || variant.(map[string]any)["type"] == "null"
|
||||
}
|
||||
}
|
||||
if !nullable {
|
||||
t.Errorf("%s.%s must preserve unknown/null", schema, field)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, schema := range []string{"JobSummary", "RunSummary"} {
|
||||
properties := documentObject(t, schemas, schema, "properties")
|
||||
if properties["attempts"] != nil || properties["queue_ahead"] != nil {
|
||||
t.Errorf("%s incorrectly promises detail-only fields", schema)
|
||||
}
|
||||
}
|
||||
expiry := documentObject(t, schemas, "APIKeyInput", "properties", "expires_in_days")
|
||||
if expiry["minimum"] != float64(1) || expiry["maximum"] != float64(365) {
|
||||
t.Errorf("key expiry bounds = %v", expiry)
|
||||
}
|
||||
profiles := documentObject(t, schemas, "JobInput", "properties", "profile_ids")
|
||||
if profiles["minItems"] != float64(1) || profiles["maxItems"] != float64(12) || profiles["uniqueItems"] != true {
|
||||
t.Errorf("profile selection bounds = %v", profiles)
|
||||
}
|
||||
paths := documentObject(t, document, "paths")
|
||||
for _, path := range []string{"/uploads/{id}/content", "/artifacts/{id}/content"} {
|
||||
responses := documentObject(t, paths, path, "get", "responses")
|
||||
for _, code := range []string{"200", "206", "304", "416"} {
|
||||
if responses[code] == nil {
|
||||
t.Errorf("%s missing binary/conditional response %s", path, code)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAPILocalReferencesResolve(t *testing.T) {
|
||||
document := servedOpenAPI(t)
|
||||
var visit func(any)
|
||||
visit = func(value any) {
|
||||
switch node := value.(type) {
|
||||
case map[string]any:
|
||||
if ref, ok := node["$ref"].(string); ok && strings.HasPrefix(ref, "#/") {
|
||||
var target any = document
|
||||
for _, part := range strings.Split(strings.TrimPrefix(ref, "#/"), "/") {
|
||||
object, ok := target.(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("broken local reference %s", ref)
|
||||
}
|
||||
target = object[part]
|
||||
}
|
||||
if target == nil {
|
||||
t.Errorf("unresolved local reference %s", ref)
|
||||
}
|
||||
}
|
||||
for _, child := range node {
|
||||
visit(child)
|
||||
}
|
||||
case []any:
|
||||
for _, child := range node {
|
||||
visit(child)
|
||||
}
|
||||
}
|
||||
}
|
||||
visit(document)
|
||||
}
|
||||
+13
-13
@@ -132,21 +132,21 @@ func (v *Settings) validate(filename string) error {
|
||||
}
|
||||
func (s *Server) jobRoutes() {
|
||||
m := s.mux
|
||||
m.HandleFunc("POST /api/v1/uploads", s.protected(false, s.upload))
|
||||
m.HandleFunc("GET /api/v1/uploads/{id}/content", s.protected(false, s.uploadContent))
|
||||
m.HandleFunc("POST /api/v1/jobs", s.protected(false, s.createJob))
|
||||
m.HandleFunc("GET /api/v1/jobs", s.protected(false, s.jobs))
|
||||
m.HandleFunc("GET /api/v1/jobs/{id}", s.protected(false, s.getJob))
|
||||
m.HandleFunc("POST /api/v1/jobs/{id}/cancel", s.protected(false, s.cancelJob))
|
||||
m.HandleFunc("POST /api/v1/jobs/{id}/retry", s.protected(false, s.retryJob))
|
||||
m.HandleFunc("GET /api/v1/jobs/{id}/events", s.protected(false, s.events))
|
||||
m.HandleFunc("GET /api/v1/jobs/{id}/artifacts", s.protected(false, s.artifacts))
|
||||
m.HandleFunc("GET /api/v1/artifacts/{id}/content", s.protected(false, s.artifactContent))
|
||||
m.HandleFunc("GET /api/v1/attempts/{id}/video", s.protected(false, s.video))
|
||||
m.HandleFunc("GET /api/v1/profiles", s.protected(false, func(w http.ResponseWriter, r *http.Request) {
|
||||
m.HandleFunc("POST /api/v1/uploads", s.protectedScope(false, "uploads:write", s.upload))
|
||||
m.HandleFunc("GET /api/v1/uploads/{id}/content", s.protectedScope(false, "uploads:read", s.uploadContent))
|
||||
m.HandleFunc("POST /api/v1/jobs", s.protectedScope(false, "jobs:write", s.createJob))
|
||||
m.HandleFunc("GET /api/v1/jobs", s.protectedScope(false, "jobs:read", s.jobs))
|
||||
m.HandleFunc("GET /api/v1/jobs/{id}", s.protectedScope(false, "jobs:read", s.getJob))
|
||||
m.HandleFunc("POST /api/v1/jobs/{id}/cancel", s.protectedScope(false, "jobs:write", s.cancelJob))
|
||||
m.HandleFunc("POST /api/v1/jobs/{id}/retry", s.protectedScope(false, "jobs:write", s.retryJob))
|
||||
m.HandleFunc("GET /api/v1/jobs/{id}/events", s.protectedScope(false, "jobs:read", s.events))
|
||||
m.HandleFunc("GET /api/v1/jobs/{id}/artifacts", s.protectedScope(false, "artifacts:read", s.artifacts))
|
||||
m.HandleFunc("GET /api/v1/artifacts/{id}/content", s.protectedScope(false, "artifacts:read", s.artifactContent))
|
||||
m.HandleFunc("GET /api/v1/attempts/{id}/video", s.protectedScope(false, "artifacts:read", s.video))
|
||||
m.HandleFunc("GET /api/v1/profiles", s.protectedScope(false, "profiles:read", func(w http.ResponseWriter, r *http.Request) {
|
||||
s.list(w, r, `SELECT to_jsonb(p) FROM profiles p ORDER BY name`)
|
||||
}))
|
||||
m.HandleFunc("GET /api/v1/dashboard", s.protected(false, s.dashboard))
|
||||
m.HandleFunc("GET /api/v1/dashboard", s.protectedScope(false, "jobs:read", s.dashboard))
|
||||
}
|
||||
|
||||
const ownerStorageQuery = `SELECT COALESCE((SELECT sum(size) FROM uploads WHERE owner_id=$1),0)+COALESCE((SELECT sum(a.size) FROM artifacts a JOIN jobs j ON j.id=a.job_id WHERE j.owner_id=$1),0)`
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -130,11 +130,24 @@ func (s *Server) origin(w http.ResponseWriter, r *http.Request) bool {
|
||||
return true
|
||||
}
|
||||
func (s *Server) protected(admin bool, h http.HandlerFunc) http.HandlerFunc {
|
||||
return s.protectedScope(admin, "", h)
|
||||
}
|
||||
|
||||
// An empty scope is session-only; new routes must opt in to automation explicitly.
|
||||
func (s *Server) protectedScope(admin bool, scope string, h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if id := r.PathValue("id"); id != "" && !uuidRE.MatchString(id) {
|
||||
fail(w, 404, "not_found", "Resource not found")
|
||||
return
|
||||
}
|
||||
if _, present := r.Header["Authorization"]; present {
|
||||
a, ok := s.authenticateAPIKey(w, r, scope)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
h(w, r.WithContext(context.WithValue(r.Context(), authKey{}, a)))
|
||||
return
|
||||
}
|
||||
c, err := r.Cookie("otche_session")
|
||||
if err != nil || len(c.Value) != 64 {
|
||||
fail(w, 401, "unauthenticated", "Sign in required")
|
||||
@@ -226,6 +239,8 @@ func (s *Server) routes() {
|
||||
m.HandleFunc("POST /api/v1/auth/login", s.login)
|
||||
m.HandleFunc("GET /api/v1/auth/session", s.protected(false, s.session))
|
||||
m.HandleFunc("POST /api/v1/auth/logout", s.protected(false, s.logout))
|
||||
s.apiKeyRoutes()
|
||||
s.documentationRoutes()
|
||||
s.jobRoutes()
|
||||
s.adminRoutes()
|
||||
}
|
||||
@@ -234,6 +249,10 @@ func (s *Server) session(w http.ResponseWriter, r *http.Request) {
|
||||
jsonResponse(w, 200, map[string]any{"user": map[string]string{"id": a.ID, "username": a.Username, "role": a.Role}, "csrf_token": a.CSRF})
|
||||
}
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
if _, present := r.Header["Authorization"]; present {
|
||||
s.authenticateAPIKey(w, r, "")
|
||||
return
|
||||
}
|
||||
if !s.origin(w, r) {
|
||||
return
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user