package api import ( "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/hex" "encoding/json" "errors" "io" "log/slog" "net" "net/http" "os" "regexp" "strings" "time" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/crypto/bcrypt" "otche/internal/store" ) type Config struct { Origin, ArtifactRoot string SecureCookies bool MaxUploadBytes, MaxOwnerBytes int64 MaxQueuedJobs int } type Server struct { db *pgxpool.Pool cfg Config mux *http.ServeMux dummyHash []byte } type identity struct { ID, Username, Role, CSRF, TokenHash string RestrictedJobResponse bool } type authKey struct{} var uuidRE = regexp.MustCompile(`^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`) var usernameRE = regexp.MustCompile(`^[A-Za-z0-9_.-]{3,64}$`) func New(db *pgxpool.Pool, c Config) (*Server, error) { if os.Getenv("PUBLIC_ORIGIN") == "" { slog.Warn("PUBLIC_ORIGIN is unset; configure the external origin before exposing the API") } if os.Getenv("ALLOW_INSECURE_HTTP") == "true" { addr := os.Getenv("LISTEN_ADDR") if addr == "" { addr = ":8080" } host, _, err := net.SplitHostPort(addr) if err != nil || !strings.EqualFold(host, "localhost") && !net.ParseIP(host).IsLoopback() { slog.Warn("ALLOW_INSECURE_HTTP is enabled on a non-loopback listener; session cookies are not secure and HTTP must not be exposed to untrusted networks", "listen_addr", addr) } } if c.Origin == "" || c.ArtifactRoot == "" { return nil, errors.New("origin and artifact root required") } if c.MaxUploadBytes <= 0 { c.MaxUploadBytes = 512 << 20 } if c.MaxOwnerBytes <= 0 { c.MaxOwnerBytes = 8 << 30 } if c.MaxQueuedJobs <= 0 { c.MaxQueuedJobs = 20 } if e := os.MkdirAll(c.ArtifactRoot, 0700); e != nil { return nil, e } h, e := bcrypt.GenerateFromPassword([]byte(randomToken()), 12) if e != nil { return nil, e } s := &Server{db: db, cfg: c, mux: http.NewServeMux(), dummyHash: h} s.routes() return s, nil } func randomToken() string { b := make([]byte, 32) if _, e := rand.Read(b); e != nil { panic(e) } return hex.EncodeToString(b) } func hashToken(v string) string { h := sha256.Sum256([]byte(v)); return hex.EncodeToString(h[:]) } func jsonResponse(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) } func fail(w http.ResponseWriter, status int, code, message string) { jsonResponse(w, status, map[string]any{"error": map[string]string{"code": code, "message": message}}) } func decode(w http.ResponseWriter, r *http.Request, v any) bool { r.Body = http.MaxBytesReader(w, r.Body, 64<<10) d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if e := d.Decode(v); e != nil { fail(w, 400, "invalid_request", "Invalid JSON request") return false } if e := d.Decode(new(any)); e != io.EOF { fail(w, 400, "invalid_request", "Expected one JSON value") return false } return true } func user(r *http.Request) identity { return r.Context().Value(authKey{}).(identity) } func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") w.Header().Set("Cache-Control", "no-store") w.Header().Set("Referrer-Policy", "no-referrer") w.Header().Set("Content-Security-Policy", "default-src 'none'; sandbox") defer func() { if recover() != nil { slog.Error("API request panicked") fail(w, 500, "internal_error", "Request failed") } }() s.mux.ServeHTTP(w, r) } func (s *Server) origin(w http.ResponseWriter, r *http.Request) bool { if r.Header.Get("Origin") != s.cfg.Origin { fail(w, 403, "origin_rejected", "Origin is not allowed") return false } 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") return } a := identity{TokenHash: hashToken(c.Value)} err = s.db.QueryRow(r.Context(), `SELECT u.id::text,u.username,u.role,s.csrf_token FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=$1 AND s.expires_at>now() AND NOT u.disabled`, a.TokenHash).Scan(&a.ID, &a.Username, &a.Role, &a.CSRF) if errors.Is(err, pgx.ErrNoRows) { fail(w, 401, "unauthenticated", "Session expired") return } if err != nil { s.dbError(w, err) return } if admin && a.Role != "admin" { fail(w, 403, "forbidden", "Administrator required") return } if r.Method != "GET" && r.Method != "HEAD" { if !s.origin(w, r) { return } if subtle.ConstantTimeCompare([]byte(r.Header.Get("X-CSRF-Token")), []byte(a.CSRF)) != 1 { fail(w, 403, "csrf_rejected", "CSRF token required") return } } h(w, r.WithContext(context.WithValue(r.Context(), authKey{}, a))) } } func (s *Server) dbError(w http.ResponseWriter, e error) { if errors.Is(e, pgx.ErrNoRows) { fail(w, 404, "not_found", "Resource not found") return } slog.Error("database operation failed", "type", "query") fail(w, 500, "internal_error", "Database operation failed") } func (s *Server) queryObject(ctx context.Context, q string, args ...any) (map[string]any, error) { var b []byte e := s.db.QueryRow(ctx, q, args...).Scan(&b) if e != nil { return nil, e } var v map[string]any e = json.Unmarshal(b, &v) return v, e } func (s *Server) queryList(ctx context.Context, q string, args ...any) ([]map[string]any, error) { rows, e := s.db.Query(ctx, q, args...) if e != nil { return nil, e } defer rows.Close() out := []map[string]any{} for rows.Next() { var b []byte if e = rows.Scan(&b); e != nil { return nil, e } var v map[string]any if e = json.Unmarshal(b, &v); e != nil { return nil, e } out = append(out, v) } return out, rows.Err() } func (s *Server) list(w http.ResponseWriter, r *http.Request, q string, args ...any) { v, e := s.queryList(r.Context(), q, args...) if e != nil { s.dbError(w, e) return } jsonResponse(w, 200, map[string]any{"items": v}) } func (s *Server) routes() { m := s.mux m.HandleFunc("GET /api/v1/health", func(w http.ResponseWriter, r *http.Request) { ctx, c := context.WithTimeout(r.Context(), 2*time.Second) defer c() if s.db.Ping(ctx) != nil { fail(w, 503, "unavailable", "Database unavailable") return } jsonResponse(w, 200, map[string]string{"status": "ok"}) }) 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() } func (s *Server) session(w http.ResponseWriter, r *http.Request) { a := user(r) 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 } var in struct { Username string `json:"username"` Password string `json:"password"` } if !decode(w, r, &in) { return } if !usernameRE.MatchString(in.Username) || len(in.Password) > 72 { fail(w, 401, "invalid_credentials", "Invalid username or password") return } // Account-scoped failures cannot collapse every proxied user into nginx's IP. // No client-supplied forwarding header is trusted for authentication policy. tx, err := s.db.Begin(r.Context()) if err != nil { s.dbError(w, err) return } defer tx.Rollback(r.Context()) key := hashToken("account:" + strings.ToLower(in.Username)) _, err = tx.Exec(r.Context(), `INSERT INTO login_limits(key,failures,reset_at) VALUES($1,0,now()+interval '15 minutes') ON CONFLICT DO NOTHING`, key) if err != nil { s.dbError(w, err) return } var failures int err = tx.QueryRow(r.Context(), `SELECT CASE WHEN reset_at>now() THEN failures ELSE 0 END FROM login_limits WHERE key=$1 FOR UPDATE`, key).Scan(&failures) if err != nil { s.dbError(w, err) return } if failures >= 15 { w.Header().Set("Retry-After", "900") fail(w, 429, "rate_limited", "Too many failed login attempts for this account") return } a := identity{} var hash string var disabled bool err = tx.QueryRow(r.Context(), `SELECT id::text,username,role,password_hash,disabled FROM users WHERE username=$1`, in.Username).Scan(&a.ID, &a.Username, &a.Role, &hash, &disabled) missing := errors.Is(err, pgx.ErrNoRows) if err != nil && !missing { s.dbError(w, err) return } if missing { hash = string(s.dummyHash) } match := bcrypt.CompareHashAndPassword([]byte(hash), []byte(in.Password)) == nil if missing || !match || disabled { _, err = tx.Exec(r.Context(), `UPDATE login_limits SET failures=$2,reset_at=CASE WHEN reset_at<=now() THEN now()+interval '15 minutes' ELSE reset_at END WHERE key=$1`, key, failures+1) if err == nil { err = tx.Commit(r.Context()) } if err != nil { s.dbError(w, err) return } fail(w, 401, "invalid_credentials", "Invalid username or password") return } token := randomToken() a.CSRF = randomToken() _, err = tx.Exec(r.Context(), `DELETE FROM login_limits WHERE key=$1`, key) if err == nil { _, err = tx.Exec(r.Context(), `INSERT INTO sessions(token_hash,user_id,csrf_token,expires_at) VALUES($1,$2,$3,now()+interval '12 hours')`, hashToken(token), a.ID, a.CSRF) } if err == nil { err = tx.Commit(r.Context()) } if err != nil { s.dbError(w, err) return } http.SetCookie(w, &http.Cookie{Name: "otche_session", Value: token, Path: "/api", HttpOnly: true, Secure: s.cfg.SecureCookies, SameSite: http.SameSiteStrictMode, MaxAge: 43200}) s.session(w, r.WithContext(context.WithValue(r.Context(), authKey{}, a))) } func (s *Server) logout(w http.ResponseWriter, r *http.Request) { _, e := s.db.Exec(r.Context(), `DELETE FROM sessions WHERE token_hash=$1`, user(r).TokenHash) if e != nil { s.dbError(w, e) return } http.SetCookie(w, &http.Cookie{Name: "otche_session", Value: "", Path: "/api", HttpOnly: true, Secure: s.cfg.SecureCookies, SameSite: http.SameSiteStrictMode, MaxAge: -1}) w.WriteHeader(204) } func CreateUser(ctx context.Context, db *pgxpool.Pool, username, password, role string) (string, error) { if !usernameRE.MatchString(username) || len(password) < 14 || len(password) > 72 || strings.TrimSpace(password) != password || role != "admin" && role != "operator" { return "", errors.New("username must be 3-64 safe characters, password 14-72 bytes, role admin/operator") } h, e := bcrypt.GenerateFromPassword([]byte(password), 12) if e != nil { return "", e } id := store.NewID() _, e = db.Exec(ctx, `INSERT INTO users(id,username,password_hash,role)VALUES($1,$2,$3,$4)`, id, username, string(h), role) return id, e }