🔒 Require login-ready user creation

This commit is contained in:
eust-w 2026-06-17 20:32:01 +08:00
parent d82989ae18
commit a3b2b07548
8 changed files with 83 additions and 10 deletions

View File

@ -125,7 +125,7 @@ Explicit startup values are validated before API/worker startup, before Kubernet
Development and acceptance entrypoints resolve API endpoints through shared helpers instead of each script carrying its own localhost default. Node/Vite entrypoints use `scripts/lib/service-endpoints.mjs`, Python operational scripts use `scripts/lib/droboticflow_env.py`, and shell wrappers use `scripts/lib/service-endpoints.sh`. `BASE_URL` is accepted by browser-oriented acceptance scripts, while deployment/reconcile wrappers preserve `API_BASE_URL` as their primary environment variable. Explicit endpoint values must be absolute `http://` or `https://` URLs so malformed values fail before Vite, curl, Playwright, or urllib requests are attempted. Browser-side `VITE_API_BASE_URL` follows the same rule, with the empty value reserved for same-origin API requests.
The frontend never reads the AI key directly. Workflow generation and operator generation are proxied through the Go API so secrets stay on the server side.
The settings page can update K8s access details, the worker defaults, the global `timezone`, `provider`, `baseURL`, `model`, and the server-side AI key. `GET /api/settings` only returns whether secrets exist via `k8s.hasKubeconfig` / `ai.hasAPIKey`; it does not echo plaintext kubeconfig or API keys back to the browser. When session auth is required, `/api/settings`, `/api/users`, database browser routes, Mongo connection tests, and external business-DB token management are organization-admin surfaces. Non-admin pages use `/api/public/settings`, which exposes only `timezone`, and users can update only their own sidebar `name` / `email` through `/api/users/me`. Worker polling and concurrency values are positive-integer gated in the browser, the shared settings payload builder, and the API, so values such as `0`, `1.5`, `60s`, or blank strings fail instead of being ignored. Default CPU/MEM resource values are trimmed and validated as positive Kubernetes resource quantities when settings are saved, and default GPU must be a positive integer when present. Timestamps in the UI are rendered in the configured IANA timezone with compact minute-level formatting for cards, lists, and summaries, while logs keep finer granularity when needed. OSS-related bucket and path settings belong on OSS operators in workflows, not in the global system settings page. Scan workflows can now reference reusable BOS storage connections via `scanConfig.connectionId`, so endpoint and AK/SK are stored once in `/api/storage/connections` and resolved by the API/worker at preview and execution time instead of being duplicated into each workflow; if a scan config or connection omits endpoint, both API preview and worker execution use the validated `BOS_ENDPOINT` startup value when it is set, otherwise real BOS requests fail with an explicit missing-endpoint error.
The settings page can update K8s access details, the worker defaults, the global `timezone`, `provider`, `baseURL`, `model`, and the server-side AI key. `GET /api/settings` only returns whether secrets exist via `k8s.hasKubeconfig` / `ai.hasAPIKey`; it does not echo plaintext kubeconfig or API keys back to the browser. When session auth is required, `/api/settings`, `/api/users`, database browser routes, Mongo connection tests, and external business-DB token management are organization-admin surfaces; creating a user requires an initial password. Model-backed AI generation requires admin/operator role. Non-admin pages use `/api/public/settings`, which exposes only `timezone`, and users can update only their own sidebar `name` / `email` through `/api/users/me`. Worker polling and concurrency values are positive-integer gated in the browser, the shared settings payload builder, and the API, so values such as `0`, `1.5`, `60s`, or blank strings fail instead of being ignored. Default CPU/MEM resource values are trimmed and validated as positive Kubernetes resource quantities when settings are saved, and default GPU must be a positive integer when present. Timestamps in the UI are rendered in the configured IANA timezone with compact minute-level formatting for cards, lists, and summaries, while logs keep finer granularity when needed. OSS-related bucket and path settings belong on OSS operators in workflows, not in the global system settings page. Scan workflows can now reference reusable BOS storage connections via `scanConfig.connectionId`, so endpoint and AK/SK are stored once in `/api/storage/connections` and resolved by the API/worker at preview and execution time instead of being duplicated into each workflow; if a scan config or connection omits endpoint, both API preview and worker execution use the validated `BOS_ENDPOINT` startup value when it is set, otherwise real BOS requests fail with an explicit missing-endpoint error.
The API now includes a cookie-session account foundation for organization-based access. Auth endpoints cover bootstrap, login, logout, current session, and super-admin organization/user management. Existing local deployments remain compatible by default; public LoadBalancer deploys require `DROBOTICFLOW_REQUIRE_SESSION_AUTH=true` so browser business APIs keep role checks. Session-authenticated unsafe requests use a double-submit `droboticflow_csrf` cookie plus `X-Droboticflow-CSRF-Token` header. Browser JSON, object-storage preview, and multipart object upload requests share the same credentials and CSRF header path; object-storage preview byte-count headers are accepted only when they are exact safe non-negative integers. Worker control endpoints under `/worker-api` require an admin/operator session, or an API token when session auth is not enforced. Bundled smoke and reconcile scripts can log in with `DROBOTICFLOW_SMOKE_EMAIL` / `DROBOTICFLOW_SMOKE_PASSWORD` and will send CSRF headers on writes. Do not embed `DROBOTICFLOW_API_TOKEN` into frontend builds; it is intended for machine-to-machine calls only.

View File

@ -12,6 +12,8 @@ Base path: `/api`
- `POST /api/ai/workflows/generate`: generate a workflow graph from natural language and the current operator catalog
- `GET /api/dashboard`: aggregate counts for projects, operators, jobs, and audits
When `DROBOTICFLOW_REQUIRE_SESSION_AUTH=true`, AI generation routes require an admin or operator session. Auditors can read existing workflows, runs, and status surfaces but cannot trigger model-backed generation.
### Auth and Organizations
- `GET /api/public/settings`: unauthenticated public settings surface; currently returns only `timezone`
@ -319,8 +321,10 @@ Sampling tasks are synced from real `audit-samples.json` run artifacts. The API
### Users and Settings
- `GET /api/users`
- `POST /api/users`
- `PUT /api/users/me`
- `PUT /api/users/:id`
- `DELETE /api/users/:id`
- `GET /api/storage/connections`
- `POST /api/storage/connections`
- `GET /api/storage/connections/:id`
@ -334,7 +338,7 @@ Sampling tasks are synced from real `audit-samples.json` run artifacts. The API
- `GET /api/settings`
- `PUT /api/settings`
When `DROBOTICFLOW_REQUIRE_SESSION_AUTH=true`, management reads and writes match the sidebar role model: `/api/users`, `/api/settings`, database browser routes, and `/api/external/business-db/tokens` are admin-only. Operators and auditors can still update their own profile through `PUT /api/users/me`, which accepts only `name` and `email` and never changes role, status, password, or organization. The reusable storage and Mongo connection list/get endpoints remain available to authenticated business users so workflow editors can select existing connections; creating, updating, deleting, and testing connections requires admin.
When `DROBOTICFLOW_REQUIRE_SESSION_AUTH=true`, management reads and writes match the sidebar role model: `/api/users`, `/api/settings`, database browser routes, and `/api/external/business-db/tokens` are admin-only. `POST /api/users` must include an initial `password` in session-auth deployments so created users can log in immediately. Operators and auditors can still update their own profile through `PUT /api/users/me`, which accepts only `name` and `email` and never changes role, status, password, or organization. User storage-path favorites are self-or-admin scoped. The reusable storage and Mongo connection list/get endpoints remain available to authenticated business users so workflow editors can select existing connections; creating, updating, deleting, and testing connections requires admin.
`POST /api/storage/connections`

View File

@ -12,7 +12,7 @@ This note tracks the production-facing safeguards that must stay true for Drobod
- Manifest rendering, image build, and deployment wrappers reject invalid Kubernetes namespace/Secret/PVC/Service names, non-absolute workspace mount paths, malformed worker/AI/BOS service URLs, and malformed image references before emitting manifests, building images, or calling `kubectl`. Multi-line ConfigMap block values are indented before manifest output so formatted GPU tolerations JSON and multi-line shell command policy regexes remain valid YAML.
- Local development and acceptance endpoints are resolved through shared helpers instead of per-script localhost literals. Vite dev proxy targets can be overridden with `VITE_DEV_API_BASE_URL` and `VITE_DEV_WORKER_BASE_URL`; browser-oriented acceptance scripts accept `BASE_URL` or `API_BASE_URL`, while reconcile/deploy wrappers keep `API_BASE_URL` as the primary operational variable. Explicit endpoint values must be absolute `http://` or `https://` URLs and fail before Vite, curl, Playwright, or urllib requests are attempted. Browser-side `VITE_API_BASE_URL` follows the same absolute http(s) rule, with an empty value reserved for same-origin API calls. Deployed smoke runs should set `SMOKE_REQUIRE_EXPLICIT_ENDPOINT=true` so an omitted endpoint cannot fall back to localhost.
- Data reconciliation uses real API calls and supports protected deployments through `DROBOTICFLOW_API_TOKEN` or session login credentials plus CSRF headers. Public session-auth environments must use an organization admin account for reconcile because it updates settings and management resources.
- Session-auth management surfaces are admin-only on both read and write paths. `/api/users`, `/api/settings`, database browser routes, Mongo connection tests, and external business-DB token management require an organization admin; `/api/public/settings` exposes only the runtime timezone so non-admin pages can render timestamps without receiving K8s, AI, Mongo, or token metadata. Users update their own sidebar profile through `PUT /api/users/me`, which accepts only `name` and `email`.
- Session-auth management surfaces are admin-only on both read and write paths. `/api/users`, `/api/settings`, database browser routes, Mongo connection tests, and external business-DB token management require an organization admin; session-auth user creation requires an initial password so new accounts are immediately login-capable. `/api/public/settings` exposes only the runtime timezone so non-admin pages can render timestamps without receiving K8s, AI, Mongo, or token metadata. Users update their own sidebar profile through `PUT /api/users/me`, which accepts only `name` and `email`; user storage-path favorites are self-or-admin scoped. Model-backed AI generation routes require admin/operator role rather than auditor access.
- Python live-acceptance and WJZH regression scripts use the shared `DroboticflowClient` helper for API token headers, session-login cookies, CSRF propagation, JSON calls, and binary object-storage calls. WJZH quality thresholds are caller-supplied through `QUALITY_MIN_CLARITY`, `QUALITY_MAX_SHAKE`, and `QUALITY_MAX_HAND_OCCLUSION`; window, slicing, and annotation timing are caller-supplied through the documented `*_SECONDS` values; sampling thresholds are caller-supplied through `SAMPLING_RULES_JSON`. The scripts do not carry built-in audit rules. New Python acceptance scripts should reuse that helper instead of carrying their own auth/request stack.
- Python WJZH and X-platform acceptance scripts validate quality thresholds through the shared normalized-threshold gate. `QUALITY_MIN_CLARITY`, `QUALITY_MAX_SHAKE`, `QUALITY_MAX_HAND_OCCLUSION`, `XPLATFORM_MIN_CLARITY`, `XPLATFORM_MAX_SHAKE`, and `XPLATFORM_MAX_HAND_OCCLUSION` must be finite values in `[0, 1]`; invalid values fail before live workflows are created.
- Python WJZH and X-platform acceptance scripts also share the same sampling-rule validator. `SAMPLING_RULES_JSON` and `XPLATFORM_RULES_JSON` must be non-empty rule arrays with unique `id` values, supported operators, required `field`/`value` fields, and finite numeric `samplePercent` values in `(0, 100]`; boolean `samplePercent` values are rejected before creating live workflows instead of being coerced to `1` or `0`.

View File

@ -745,8 +745,11 @@ func NewHandlerWithConfig(dataStore store.Store, aiService ai.Service, appConfig
router.Post("/worker-api/runs/{id}/retry", instance.handleWorkerAPIRetry)
})
router.Get("/api/ai/status", instance.handleAIStatus)
router.Post("/api/ai/operators/generate", instance.handleAIOperatorGenerate)
router.Post("/api/ai/workflows/generate", instance.handleAIWorkflowGenerate)
router.Group(func(router chi.Router) {
router.Use(instance.requireBusinessRole(domain.UserRoleAdmin, domain.UserRoleOperator))
router.Post("/api/ai/operators/generate", instance.handleAIOperatorGenerate)
router.Post("/api/ai/workflows/generate", instance.handleAIWorkflowGenerate)
})
router.Get("/api/dashboard", instance.handleDashboard)
router.Get("/api/projects", instance.handleProjectsList)
@ -2817,6 +2820,10 @@ func (server *server) handleUsersCreate(writer http.ResponseWriter, request *htt
renderValidationError(writer, validationIssue{Field: "role", Message: "role must be admin, auditor, or operator"})
return
}
if server.requireSessionAuth && strings.TrimSpace(payload.Password) == "" {
renderValidationError(writer, validationIssue{Field: "password", Message: "password is required"})
return
}
if strings.TrimSpace(payload.Password) != "" {
passwordHash, err := hashPassword(payload.Password)
if err != nil {

View File

@ -543,6 +543,12 @@ func TestSessionAuthTenantIsolationAndRolePermissions(t *testing.T) {
if auditorProjectRecorder.Code != http.StatusForbidden {
t.Fatalf("expected auditor project create to be forbidden, got %d body=%s", auditorProjectRecorder.Code, auditorProjectRecorder.Body.String())
}
for _, path := range []string{"/api/ai/operators/generate", "/api/ai/workflows/generate"} {
recorder := serveJSONWithCookie(handler, http.MethodPost, path, []byte(`{"description":"generate test"}`), auditorCookie)
if recorder.Code != http.StatusForbidden {
t.Fatalf("expected auditor POST %s to be forbidden, got %d body=%s", path, recorder.Code, recorder.Body.String())
}
}
publicSettingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(publicSettingsRecorder, httptest.NewRequest(http.MethodGet, "/api/public/settings", nil))
@ -567,6 +573,43 @@ func TestSessionAuthTenantIsolationAndRolePermissions(t *testing.T) {
t.Fatalf("admin settings get = %d body=%s", adminSettingsRecorder.Code, adminSettingsRecorder.Body.String())
}
userWithoutPasswordRecorder := serveJSONWithCookie(
handler,
http.MethodPost,
"/api/users",
[]byte(`{"name":"No Password","email":"no-password@example.com","role":"operator"}`),
adminACookie,
)
if userWithoutPasswordRecorder.Code != http.StatusBadRequest {
t.Fatalf("expected session user create without password to fail, got %d body=%s", userWithoutPasswordRecorder.Code, userWithoutPasswordRecorder.Body.String())
}
userWithPasswordRecorder := serveJSONWithCookie(
handler,
http.MethodPost,
"/api/users",
[]byte(`{"name":"Created Operator","email":"created-operator@example.com","role":"operator","password":"created-operator-pass"}`),
adminACookie,
)
if userWithPasswordRecorder.Code != http.StatusCreated {
t.Fatalf("session user create with password = %d body=%s", userWithPasswordRecorder.Code, userWithPasswordRecorder.Body.String())
}
var createdSessionUser domain.UserRecord
if err := json.Unmarshal(userWithPasswordRecorder.Body.Bytes(), &createdSessionUser); err != nil {
t.Fatalf("decode created session user: %v", err)
}
if createdSessionUser.PasswordHash != "" {
t.Fatalf("session user create leaked password hash: %s", userWithPasswordRecorder.Body.String())
}
storedSessionUser, err := dataStore.GetUser(context.Background(), createdSessionUser.ID)
if err != nil {
t.Fatalf("load created session user: %v", err)
}
if storedSessionUser == nil || strings.TrimSpace(storedSessionUser.PasswordHash) == "" {
t.Fatalf("expected created session user to store password hash, got %#v", storedSessionUser)
}
_ = loginSession(t, handler, createdSessionUser.Email, "created-operator-pass")
operatorCookie := loginSession(t, handler, operatorA.Email, "operator-a-pass")
adminOnlyPaths := []string{
"/api/users",

View File

@ -17,7 +17,7 @@ interface UserContextType {
error: string | null;
refreshUsers: (options?: { silent?: boolean }) => Promise<User[]>;
selectUser: (userId: string) => void;
createUser: (payload: Pick<User, "name" | "email" | "role">) => Promise<User>;
createUser: (payload: Pick<User, "name" | "email" | "role"> & { password?: string }) => Promise<User>;
updateCurrentUser: (payload: Partial<Pick<User, "name" | "email">>) => Promise<User | null>;
login: (payload: { email: string; password: string }) => Promise<User>;
bootstrapSuperAdmin: (payload: { name: string; email: string; password: string }) => Promise<User>;
@ -130,7 +130,7 @@ export function UserProvider({ children }: { children: ReactNode }) {
[users],
);
const createUser = useCallback(async (payload: Pick<User, "name" | "email" | "role">) => {
const createUser = useCallback(async (payload: Pick<User, "name" | "email" | "role"> & { password?: string }) => {
const created = await usersApi.create(payload);
setUsers((previous) => [created, ...previous]);
setCurrentUser(created);

View File

@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useState } from "react";
import { cn } from "../lib/utils";
import { X, User, Shield, Mail, Plus, Trash2 } from "lucide-react";
import { KeyRound, X, User, Shield, Mail, Plus, Trash2 } from "lucide-react";
import { useUser } from "../context/UserContext";
import type { User as UserData } from "../types";
import { usersApi } from "../services/api/users";
@ -12,6 +12,7 @@ export default function Users() {
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalMode, setModalMode] = useState<"create" | "edit">("edit");
const [error, setError] = useState("");
const [createPassword, setCreatePassword] = useState("");
const loadUsers = useCallback(async () => {
setError("");
@ -34,11 +35,13 @@ export default function Users() {
const handleEdit = (user: UserData) => {
setModalMode("edit");
setEditingUser({ ...user });
setCreatePassword("");
setIsModalOpen(true);
};
const handleCreate = () => {
setModalMode("create");
setCreatePassword("");
setEditingUser({
id: "",
name: "",
@ -56,6 +59,7 @@ export default function Users() {
name: editingUser.name,
email: editingUser.email,
role: editingUser.role,
password: createPassword,
})
: usersApi.update(editingUser.id, editingUser);
@ -209,6 +213,20 @@ export default function Users() {
<option value="operator">Operator</option>
</select>
</div>
{modalMode === "create" && (
<div className="space-y-1.5">
<label className="text-xs font-medium text-gray-400 uppercase tracking-wider flex items-center gap-1.5">
<KeyRound className="w-3 h-3" /> 初始密码
</label>
<input
type="password"
className="w-full bg-[#0a0a0a] border border-[#2a2b2f] rounded-md px-4 py-2 text-sm focus:outline-none focus:border-blue-500 text-white"
value={createPassword}
onChange={(event) => setCreatePassword(event.target.value)}
autoComplete="new-password"
/>
</div>
)}
</div>
<div className="p-6 border-t border-[#2a2b2f] flex justify-end gap-3 bg-[#0a0a0a]/50">
<button
@ -219,7 +237,8 @@ export default function Users() {
</button>
<button
onClick={handleSave}
className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium transition-all"
disabled={modalMode === "create" && !createPassword.trim()}
className="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md text-sm font-medium transition-all disabled:cursor-not-allowed disabled:opacity-50"
>
{modalMode === "create" ? "创建用户" : "保存修改"}
</button>

View File

@ -3,7 +3,7 @@ import { apiRequest } from "./client";
export const usersApi = {
list: async () => (await apiRequest<{ items: User[] }>("/api/users")).items,
create: (payload: Pick<User, "name" | "email" | "role">) =>
create: (payload: Pick<User, "name" | "email" | "role"> & { password?: string }) =>
apiRequest<User>("/api/users", { method: "POST" }, payload),
updateMe: (payload: Partial<Pick<User, "name" | "email">>) =>
apiRequest<User>("/api/users/me", { method: "PUT" }, payload),