Add OpsProof approval-gated execution
This commit is contained in:
parent
f015f2881e
commit
675404374b
|
|
@ -79,6 +79,15 @@ user identity. Incident and future mutation routes require both authentication
|
|||
and current membership in that allowlist. The overview remains a read-only
|
||||
landing page.
|
||||
|
||||
An authenticated operator may convert current incident evidence into a durable
|
||||
proposal only after supplying a rollback procedure. PostgreSQL stores the
|
||||
proposal, its evidence hash, exact command and arguments, risk, creator, and a
|
||||
separate one-time approval record. Approval reruns Doctor, requires an exact
|
||||
evidence-hash match, checks Jeannie's advertised command allowlist, validates
|
||||
the fixed argument shape, and then records the returned execution ID. The
|
||||
execution page polls that ID and persists bounded progress output; it never
|
||||
submits another command while refreshing.
|
||||
|
||||
## Security boundary
|
||||
|
||||
OpsProof is not a shell console.
|
||||
|
|
@ -106,7 +115,7 @@ Each slice should be a small, independently testable commit:
|
|||
5. remediation proposal with risk and rollback details (implemented as a
|
||||
blocked, non-executable proposal);
|
||||
6. Dex login and operator authorization (implemented);
|
||||
7. approval-gated execution and live progress;
|
||||
7. approval-gated execution and live progress (implemented);
|
||||
8. post-change validation and incident report;
|
||||
9. sanitized public demo mode and portfolio link.
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,46 @@
|
|||
package migrations
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.laravel.com/schema"
|
||||
)
|
||||
|
||||
func createOpsProofWorkflowTables(ctx context.Context) error {
|
||||
if err := schema.Create(ctx, "remediation_proposals", func(table *schema.Blueprint) {
|
||||
table.ID()
|
||||
table.String("scope")
|
||||
table.String("target")
|
||||
table.String("doctor_execution_id")
|
||||
table.String("evidence_hash")
|
||||
table.LongText("evidence_json")
|
||||
table.String("command")
|
||||
table.Text("arguments_json")
|
||||
table.String("risk_level")
|
||||
table.LongText("rollback")
|
||||
table.String("status")
|
||||
table.String("created_by")
|
||||
table.Timestamps()
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := schema.Create(ctx, "remediation_approvals", func(table *schema.Blueprint) {
|
||||
table.ID()
|
||||
table.BigInteger("proposal_id")
|
||||
table.String("operator_email")
|
||||
table.String("evidence_hash")
|
||||
table.Timestamp("approved_at")
|
||||
table.Timestamps()
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return schema.Create(ctx, "operation_executions", func(table *schema.Blueprint) {
|
||||
table.ID()
|
||||
table.BigInteger("proposal_id")
|
||||
table.String("jeannie_execution_id")
|
||||
table.String("status")
|
||||
table.LongText("output")
|
||||
table.Text("error")
|
||||
table.Timestamps()
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
package migrations
|
||||
|
||||
import "go.laravel.com/db"
|
||||
|
||||
var All = []db.Migration{
|
||||
{Name: "0001_01_01_000000_create_users_table", Run: createUsersTable},
|
||||
{Name: "0001_01_01_000001_create_cache_table", Run: createCacheTable},
|
||||
{Name: "0001_01_01_000002_create_jobs_table", Run: createJobsTable},
|
||||
{Name: "2026_12_04_000003_create_opsproof_workflow_tables", Run: createOpsProofWorkflowTables},
|
||||
}
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
package execution
|
||||
|
||||
import (
|
||||
"go.laravel.com/db"
|
||||
"go.laravel.com/inertia"
|
||||
"go.laravel.com/model"
|
||||
"go.laravel.com/web"
|
||||
|
||||
"app/models"
|
||||
"app/services"
|
||||
)
|
||||
|
||||
func Show(request *web.Request) *web.Response {
|
||||
id, err := request.PathInt("execution")
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
execution, err := model.Query[models.OperationExecution]().Find(request, id)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
proposal, err := model.Query[models.RemediationProposal]().Find(request, execution.ProposalID)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
remote, err := services.From(request.Context()).Jeannie.Execution(request.Context(), execution.JeannieExecutionID)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if err := model.Update(request, &execution, db.Values{
|
||||
"status": remote.Status, "output": remote.Output, "error": remote.Error,
|
||||
}); err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if remote.Status == "succeeded" || remote.Status == "failed" {
|
||||
if err := model.Update(request, &proposal, db.Values{"status": remote.Status}); err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
}
|
||||
return inertia.Render("Execution", inertia.Props{
|
||||
"view": inertia.Props{"execution": execution, "proposal": proposal},
|
||||
})
|
||||
}
|
||||
|
|
@ -0,0 +1,154 @@
|
|||
package proposal
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"go.laravel.com/db"
|
||||
"go.laravel.com/inertia"
|
||||
"go.laravel.com/model"
|
||||
"go.laravel.com/validation"
|
||||
"go.laravel.com/validation/rule"
|
||||
"go.laravel.com/web"
|
||||
|
||||
"app/models"
|
||||
"app/services"
|
||||
)
|
||||
|
||||
type StoreProposal struct {
|
||||
Rollback string `json:"rollback"`
|
||||
}
|
||||
|
||||
func (form *StoreProposal) Rules() validation.Rules {
|
||||
return validation.For(form, rule.Field(&form.Rollback, rule.Required, rule.Min(20), rule.Max(2000)))
|
||||
}
|
||||
|
||||
func Store(request *web.Request) *web.Response {
|
||||
scope, target := request.PathValue("scope"), request.PathValue("target")
|
||||
if !services.ValidDoctorTarget(scope, target) {
|
||||
return web.Abort(http.StatusNotFound)
|
||||
}
|
||||
form, err := request.Validate[StoreProposal]()
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
incident, err := services.From(request.Context()).Jeannie.Doctor(request.Context(), scope, target)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if incident.Proposal.Action == "" || len(incident.Proposal.EvidenceIDs) == 0 {
|
||||
return web.Abort(http.StatusConflict)
|
||||
}
|
||||
evidenceHash, err := services.EvidenceFingerprint(incident)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
evidenceJSON, err := json.Marshal(incident.Evidence)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
argumentsJSON, _ := json.Marshal([]string{scope, target, "--ai"})
|
||||
operator := models.CurrentUser(request)
|
||||
proposal := models.RemediationProposal{
|
||||
Scope: scope, Target: target, DoctorExecutionID: incident.ExecutionID,
|
||||
EvidenceHash: evidenceHash, EvidenceJSON: string(evidenceJSON), Command: "doctor",
|
||||
ArgumentsJSON: string(argumentsJSON), RiskLevel: incident.Proposal.RiskLevel,
|
||||
Rollback: form.Rollback, Status: "pending", CreatedBy: operator.Email,
|
||||
}
|
||||
if err := model.Create(request, &proposal); err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
return web.Redirect(fmt.Sprintf("/proposals/%d", proposal.ID))
|
||||
}
|
||||
|
||||
func Show(request *web.Request) *web.Response {
|
||||
id, err := request.PathInt("proposal")
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
proposal, err := model.Query[models.RemediationProposal]().Find(request, id)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
return inertia.Render("Proposal", inertia.Props{"proposal": proposal})
|
||||
}
|
||||
|
||||
func Approve(request *web.Request) *web.Response {
|
||||
id, err := request.PathInt("proposal")
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
proposal, err := model.Query[models.RemediationProposal]().Find(request, id)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if proposal.Status != "pending" {
|
||||
return web.Abort(http.StatusConflict)
|
||||
}
|
||||
client := services.From(request.Context()).Jeannie
|
||||
current, err := client.Doctor(request.Context(), proposal.Scope, proposal.Target)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
fingerprint, err := services.EvidenceFingerprint(current)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if fingerprint != proposal.EvidenceHash {
|
||||
_ = model.Update(request, &proposal, db.Values{"status": "stale"})
|
||||
return web.Abort(http.StatusConflict)
|
||||
}
|
||||
allowed, err := client.CommandAllowed(request.Context(), proposal.Command)
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if !allowed {
|
||||
return web.Abort(http.StatusForbidden)
|
||||
}
|
||||
var arguments []string
|
||||
if err := json.Unmarshal([]byte(proposal.ArgumentsJSON), &arguments); err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
if len(arguments) != 3 || arguments[0] != proposal.Scope || arguments[1] != proposal.Target || arguments[2] != "--ai" {
|
||||
return web.Abort(http.StatusForbidden)
|
||||
}
|
||||
|
||||
operator := models.CurrentUser(request)
|
||||
err = db.Transaction(request, func(ctx context.Context) error {
|
||||
locked, err := model.Query[models.RemediationProposal]().LockForUpdate().Find(ctx, proposal.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if locked.Status != "pending" {
|
||||
return fmt.Errorf("proposal is no longer pending")
|
||||
}
|
||||
approval := models.RemediationApproval{
|
||||
ProposalID: proposal.ID, OperatorEmail: operator.Email,
|
||||
EvidenceHash: proposal.EvidenceHash, ApprovedAt: time.Now().UTC(),
|
||||
}
|
||||
if err := model.Create(ctx, &approval); err != nil {
|
||||
return err
|
||||
}
|
||||
return model.Update(ctx, &locked, db.Values{"status": "approved"})
|
||||
})
|
||||
if err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
|
||||
remote, err := client.Submit(request.Context(), proposal.Command, arguments)
|
||||
if err != nil {
|
||||
_ = model.Update(request, &proposal, db.Values{"status": "submit_failed"})
|
||||
return web.Fail(err)
|
||||
}
|
||||
execution := models.OperationExecution{
|
||||
ProposalID: proposal.ID, JeannieExecutionID: remote.ID, Status: remote.Status,
|
||||
}
|
||||
if err := model.Create(request, &execution); err != nil {
|
||||
return web.Fail(err)
|
||||
}
|
||||
_ = model.Update(request, &proposal, db.Values{"status": "executing"})
|
||||
return web.Redirect(fmt.Sprintf("/executions/%d", execution.ID))
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package models
|
||||
|
||||
import "time"
|
||||
|
||||
type RemediationProposal struct {
|
||||
ID int64 `json:"id"`
|
||||
Scope string `json:"scope"`
|
||||
Target string `json:"target"`
|
||||
DoctorExecutionID string `json:"doctor_execution_id"`
|
||||
EvidenceHash string `json:"evidence_hash"`
|
||||
EvidenceJSON string `json:"evidence_json"`
|
||||
Command string `json:"command"`
|
||||
ArgumentsJSON string `json:"arguments_json"`
|
||||
RiskLevel string `json:"risk_level"`
|
||||
Rollback string `json:"rollback"`
|
||||
Status string `json:"status"`
|
||||
CreatedBy string `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RemediationApproval struct {
|
||||
ID int64 `json:"id"`
|
||||
ProposalID int64 `json:"proposal_id"`
|
||||
OperatorEmail string `json:"operator_email"`
|
||||
EvidenceHash string `json:"evidence_hash"`
|
||||
ApprovedAt time.Time `json:"approved_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type OperationExecution struct {
|
||||
ID int64 `json:"id"`
|
||||
ProposalID int64 `json:"proposal_id"`
|
||||
JeannieExecutionID string `json:"jeannie_execution_id"`
|
||||
Status string `json:"status"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
import { router } from '@inertiajs/react';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
interface ExecutionView {
|
||||
execution: {
|
||||
id: number;
|
||||
jeannie_execution_id: string;
|
||||
status: string;
|
||||
output: string;
|
||||
error: string;
|
||||
};
|
||||
proposal: {
|
||||
id: number;
|
||||
scope: string;
|
||||
target: string;
|
||||
evidence_hash: string;
|
||||
};
|
||||
}
|
||||
|
||||
export default function ExecutionPage({ view }: { view: ExecutionView }) {
|
||||
const active = view.execution.status === 'queued' || view.execution.status === 'running';
|
||||
useEffect(() => {
|
||||
if (!active) return;
|
||||
const timer = window.setInterval(() => router.reload({ only: ['view'] }), 2000);
|
||||
return () => window.clearInterval(timer);
|
||||
}, [active]);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-[#071019] px-5 py-8 text-slate-100">
|
||||
<div className="mx-auto max-w-5xl">
|
||||
<p className="text-xs uppercase tracking-[0.2em] text-cyan-300">Approval-gated execution</p>
|
||||
<h1 className="mt-3 text-3xl font-semibold">{view.proposal.scope} / {view.proposal.target}</h1>
|
||||
<div className="mt-6 rounded-2xl border border-white/10 bg-[#0a141e] p-6">
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="font-mono text-xs text-slate-500">{view.execution.jeannie_execution_id}</span>
|
||||
<span className="rounded-md border border-cyan-300/20 bg-cyan-300/10 px-2 py-1 text-xs uppercase text-cyan-200">
|
||||
{view.execution.status}
|
||||
</span>
|
||||
</div>
|
||||
<pre className="mt-5 max-h-[32rem] overflow-auto whitespace-pre-wrap rounded-xl bg-black/20 p-4 text-xs leading-5 text-slate-400">
|
||||
{view.execution.output || (active ? 'Waiting for Jeannie output…' : view.execution.error || 'No output returned.')}
|
||||
</pre>
|
||||
{active && <p className="mt-3 text-xs text-slate-500">Refreshing every two seconds.</p>}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,3 +1,6 @@
|
|||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface Evidence {
|
||||
id: string;
|
||||
status: string;
|
||||
|
|
@ -56,6 +59,13 @@ const tone: Record<string, string> = {
|
|||
|
||||
export default function IncidentPage({ laravelVersion, view, operator }: Props) {
|
||||
const incident = view.incident;
|
||||
const [rollback, setRollback] = useState('');
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
function storeProposal() {
|
||||
setSubmitting(true);
|
||||
router.post(`/incidents/${incident.scope}/${incident.target}/proposals`, { rollback }, { onFinish: () => setSubmitting(false) });
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-[#071019] text-slate-100 selection:bg-cyan-300 selection:text-slate-950">
|
||||
|
|
@ -227,13 +237,30 @@ export default function IncidentPage({ laravelVersion, view, operator }: Props)
|
|||
</code>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
disabled={!incident.proposal.readyForApproval}
|
||||
className="mt-5 w-full cursor-not-allowed rounded-lg bg-white/8 px-4 py-3 text-sm text-slate-500"
|
||||
>
|
||||
Approval unavailable until identity, authorization, and rollback controls exist
|
||||
</button>
|
||||
{incident.proposal.status === 'blocked' && (
|
||||
<div className="mt-5">
|
||||
<label htmlFor="rollback" className="text-xs uppercase tracking-[0.18em] text-slate-600">
|
||||
Operator-supplied rollback procedure
|
||||
</label>
|
||||
<textarea
|
||||
id="rollback"
|
||||
value={rollback}
|
||||
onChange={(event) => setRollback(event.target.value)}
|
||||
rows={4}
|
||||
maxLength={2000}
|
||||
placeholder="Describe the exact rollback or restoration procedure before creating the durable proposal."
|
||||
className="mt-3 w-full rounded-xl border border-white/10 bg-black/20 p-3 text-sm text-slate-300 outline-none focus:border-violet-300/50"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={storeProposal}
|
||||
disabled={submitting || rollback.trim().length < 20}
|
||||
className="mt-3 w-full rounded-lg bg-violet-300 px-4 py-3 text-sm font-semibold text-slate-950 disabled:cursor-not-allowed disabled:bg-white/8 disabled:text-slate-500"
|
||||
>
|
||||
{submitting ? 'Revalidating evidence…' : 'Create durable proposal'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,70 @@
|
|||
import { router } from '@inertiajs/react';
|
||||
import { useState } from 'react';
|
||||
|
||||
interface Proposal {
|
||||
id: number;
|
||||
scope: string;
|
||||
target: string;
|
||||
doctor_execution_id: string;
|
||||
evidence_hash: string;
|
||||
command: string;
|
||||
arguments_json: string;
|
||||
risk_level: string;
|
||||
rollback: string;
|
||||
status: string;
|
||||
created_by: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export default function ProposalPage({ proposal }: { proposal: Proposal }) {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
|
||||
function approve() {
|
||||
setSubmitting(true);
|
||||
router.post(`/proposals/${proposal.id}/approval`, {}, { onFinish: () => setSubmitting(false) });
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-[#071019] px-5 py-8 text-slate-100">
|
||||
<div className="mx-auto max-w-4xl">
|
||||
<a href={`/incidents/${proposal.scope}/${proposal.target}`} className="text-xs text-cyan-300">
|
||||
← Incident evidence
|
||||
</a>
|
||||
<section className="mt-6 overflow-hidden rounded-3xl border border-violet-300/20 bg-[#0a141e]">
|
||||
<div className="border-b border-white/10 p-7">
|
||||
<p className="text-xs uppercase tracking-[0.2em] text-violet-200">Durable proposal #{proposal.id}</p>
|
||||
<h1 className="mt-3 text-3xl font-semibold">{proposal.scope} / {proposal.target}</h1>
|
||||
<p className="mt-3 font-mono text-xs text-slate-500">Evidence SHA-256 {proposal.evidence_hash}</p>
|
||||
</div>
|
||||
<div className="grid gap-px bg-white/10 md:grid-cols-2">
|
||||
<div className="space-y-5 bg-[#0b1621] p-6">
|
||||
<p className="text-xs uppercase tracking-[0.18em] text-slate-600">Exact proposed action</p>
|
||||
<code className="block rounded-lg bg-black/20 p-3 text-xs text-violet-100">
|
||||
./jeannie {proposal.command} {JSON.parse(proposal.arguments_json).join(' ')}
|
||||
</code>
|
||||
<p className="text-sm text-slate-400">Created by {proposal.created_by}</p>
|
||||
</div>
|
||||
<div className="space-y-5 bg-[#0b1621] p-6">
|
||||
<p className="text-xs uppercase tracking-[0.18em] text-slate-600">Risk and rollback</p>
|
||||
<p className="text-sm uppercase text-rose-200">{proposal.risk_level} risk</p>
|
||||
<p className="whitespace-pre-wrap text-sm leading-6 text-slate-400">{proposal.rollback}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className="p-6">
|
||||
<p className="text-sm text-amber-200">
|
||||
Approval re-runs Doctor, compares the evidence hash, checks the Jeannie allowlist, and validates the exact arguments before submission.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={approve}
|
||||
disabled={submitting || proposal.status !== 'pending'}
|
||||
className="mt-5 w-full rounded-lg bg-violet-300 px-4 py-3 font-semibold text-slate-950 disabled:cursor-not-allowed disabled:bg-white/8 disabled:text-slate-500"
|
||||
>
|
||||
{submitting ? 'Revalidating…' : proposal.status === 'pending' ? 'Approve once and execute' : `Proposal ${proposal.status}`}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
|
@ -9,7 +9,9 @@ import (
|
|||
"go.laravel.com/web"
|
||||
|
||||
"app/handlers/authentication"
|
||||
"app/handlers/execution"
|
||||
"app/handlers/incident"
|
||||
"app/handlers/proposal"
|
||||
"app/handlers/welcome"
|
||||
appmiddleware "app/middleware"
|
||||
)
|
||||
|
|
@ -22,6 +24,10 @@ func Web(route *routing.Router, cfg *config.Config) {
|
|||
|
||||
operator := route.Middleware(auth.Authenticate{}, appmiddleware.Operator{})
|
||||
operator.Get("/incidents/{scope}/{target}", incident.Show)
|
||||
operator.Post("/incidents/{scope}/{target}/proposals", proposal.Store)
|
||||
operator.Get("/proposals/{proposal}", proposal.Show)
|
||||
operator.Post("/proposals/{proposal}/approval", proposal.Approve)
|
||||
operator.Get("/executions/{execution}", execution.Show)
|
||||
|
||||
route.Fallback(func(*web.Request) *web.Response {
|
||||
return web.Abort(http.StatusNotFound)
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ package services
|
|||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
|
@ -187,29 +188,87 @@ type execution struct {
|
|||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
type RemoteExecution struct {
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Output string `json:"output"`
|
||||
Error string `json:"error"`
|
||||
}
|
||||
|
||||
func (client *JeannieClient) CommandAllowed(ctx context.Context, command string) (bool, error) {
|
||||
var response struct {
|
||||
Commands []string `json:"commands"`
|
||||
}
|
||||
if err := client.request(ctx, http.MethodGet, "/v1/commands", nil, &response); err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, allowed := range response.Commands {
|
||||
if allowed == command {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (client *JeannieClient) Submit(ctx context.Context, command string, args []string) (RemoteExecution, error) {
|
||||
payload, err := json.Marshal(map[string]any{"command": command, "args": args})
|
||||
if err != nil {
|
||||
return RemoteExecution{}, err
|
||||
}
|
||||
var submitted RemoteExecution
|
||||
if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil {
|
||||
return RemoteExecution{}, err
|
||||
}
|
||||
if submitted.ID == "" {
|
||||
return RemoteExecution{}, errors.New("Jeannie API returned an empty execution ID")
|
||||
}
|
||||
return submitted, nil
|
||||
}
|
||||
|
||||
func (client *JeannieClient) Execution(ctx context.Context, id string) (RemoteExecution, error) {
|
||||
if !kubernetesApplicationName.MatchString(id) {
|
||||
return RemoteExecution{}, errors.New("invalid Jeannie execution ID")
|
||||
}
|
||||
var current RemoteExecution
|
||||
if err := client.request(ctx, http.MethodGet, "/v1/executions/"+id, nil, ¤t); err != nil {
|
||||
return RemoteExecution{}, err
|
||||
}
|
||||
current.Output = cleanExcerpt(current.Output, 12000)
|
||||
current.Error = cleanExcerpt(current.Error, 1200)
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func EvidenceFingerprint(incident IncidentSnapshot) (string, error) {
|
||||
payload, err := json.Marshal(struct {
|
||||
Scope string `json:"scope"`
|
||||
Target string `json:"target"`
|
||||
Evidence []IncidentEvidence `json:"evidence"`
|
||||
}{incident.Scope, incident.Target, incident.Evidence})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
hash := sha256.Sum256(payload)
|
||||
return fmt.Sprintf("%x", hash[:]), nil
|
||||
}
|
||||
|
||||
func (client *JeannieClient) execute(ctx context.Context, command string, args []string, timeout time.Duration) (execution, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
|
||||
payload, err := json.Marshal(map[string]any{"command": command, "args": args})
|
||||
submitted, err := client.Submit(ctx, command, args)
|
||||
if err != nil {
|
||||
return execution{}, fmt.Errorf("encode %s request: %w", command, err)
|
||||
}
|
||||
var submitted execution
|
||||
if err := client.request(ctx, http.MethodPost, "/v1/execute", bytes.NewReader(payload), &submitted); err != nil {
|
||||
return execution{}, fmt.Errorf("submit %s request: %w", command, err)
|
||||
}
|
||||
if submitted.ID == "" {
|
||||
return execution{}, errors.New("Jeannie API returned an empty execution ID")
|
||||
}
|
||||
|
||||
for {
|
||||
var current execution
|
||||
if err := client.request(ctx, http.MethodGet, "/v1/executions/"+submitted.ID, nil, ¤t); err != nil {
|
||||
remote, err := client.Execution(ctx, submitted.ID)
|
||||
if err != nil {
|
||||
return execution{}, fmt.Errorf("read %s execution: %w", command, err)
|
||||
}
|
||||
current := execution(remote)
|
||||
switch current.Status {
|
||||
case "queued", "running":
|
||||
timer := time.NewTimer(client.PollInterval)
|
||||
|
|
|
|||
|
|
@ -0,0 +1,55 @@
|
|||
package feature_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"go.laravel.com/laraveltest"
|
||||
|
||||
"app/models"
|
||||
"app/services"
|
||||
"app/tests"
|
||||
)
|
||||
|
||||
func TestProposalApprovalRevalidatesAndSubmitsExactDoctorAction(t *testing.T) {
|
||||
doctorRequests := 0
|
||||
server := httptest.NewServer(http.HandlerFunc(func(response http.ResponseWriter, request *http.Request) {
|
||||
switch request.URL.Path {
|
||||
case "/v1/commands":
|
||||
_, _ = response.Write([]byte(`{"commands":["doctor","status"]}`))
|
||||
case "/v1/execute":
|
||||
var payload struct {
|
||||
Args []string `json:"args"`
|
||||
}
|
||||
_ = json.NewDecoder(request.Body).Decode(&payload)
|
||||
if len(payload.Args) == 3 && payload.Args[2] == "--ai" {
|
||||
_, _ = response.Write([]byte(`{"id":"execution-approved","status":"queued"}`))
|
||||
return
|
||||
}
|
||||
doctorRequests++
|
||||
_, _ = response.Write([]byte(`{"id":"doctor-` + string(rune('0'+doctorRequests)) + `","status":"queued"}`))
|
||||
case "/v1/executions/doctor-1", "/v1/executions/doctor-2":
|
||||
_, _ = response.Write([]byte(`{"id":"doctor","status":"failed","output":"{\"title\":\"Doctor\",\"rows\":[{\"status\":\"fail\",\"area\":\"Kubernetes apps\",\"check\":\"n8n\",\"summary\":\"CrashLoopBackOff\",\"detail\":\"container exits\",\"cause\":\"startup failure\"}]}"}`))
|
||||
case "/v1/executions/execution-approved":
|
||||
_, _ = response.Write([]byte(`{"id":"execution-approved","status":"running","output":"repair in progress"}`))
|
||||
default:
|
||||
http.NotFound(response, request)
|
||||
}
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := tests.New(t, laraveltest.Env(map[string]string{"OPSPROOF_OPERATOR_EMAILS": "operator@example.test"})).ActingAs(&models.User{
|
||||
ID: 1, Name: "Operator", Email: "operator@example.test",
|
||||
})
|
||||
services.From(client.Context()).Jeannie = services.NewJeannieClient(server.URL, "test-token")
|
||||
|
||||
client.WithoutRedirects().Post("/incidents/cluster/n8n/proposals", url.Values{
|
||||
"rollback": {"Restore the previous deployment revision and verify pod readiness."},
|
||||
}).AssertRedirect("/proposals/1")
|
||||
client.Get("/proposals/1").AssertOK().AssertInertia("Proposal")
|
||||
client.WithoutRedirects().Post("/proposals/1/approval", url.Values{}).AssertRedirect("/executions/1")
|
||||
client.Get("/executions/1").AssertOK().AssertInertia("Execution").AssertProp("view.execution.status", "running")
|
||||
}
|
||||
|
|
@ -75,6 +75,11 @@ confirmed by deterministic validation.
|
|||
Keep the proposal blocked when identity, current-evidence validation, or a
|
||||
target-specific rollback is absent; rendering a command never grants the
|
||||
authority to execute it.
|
||||
- Persist proposals, approvals, and execution IDs separately. An approval is
|
||||
single-use and valid only when freshly collected evidence has the same hash,
|
||||
the command remains advertised by Jeannie, and its arguments still match the
|
||||
constrained target. Progress reads the recorded execution; it never retries
|
||||
the state-changing POST.
|
||||
|
||||
## Why not Laravel Rust now?
|
||||
|
||||
|
|
|
|||
|
|
@ -130,7 +130,7 @@ class OpsProofPipelineTests(unittest.TestCase):
|
|||
self.assertIn("Remediation proposal", incident)
|
||||
self.assertIn("Risk review", incident)
|
||||
self.assertIn("Deterministic validation", incident)
|
||||
self.assertIn("Approval unavailable until identity", incident)
|
||||
self.assertIn("Create durable proposal", incident)
|
||||
self.assertNotIn("fetch('/v1/execute", incident)
|
||||
|
||||
self.assertIn("ReadyForApproval bool", client)
|
||||
|
|
@ -150,6 +150,25 @@ class OpsProofPipelineTests(unittest.TestCase):
|
|||
self.assertIn('route.Get("/login"', routes)
|
||||
self.assertIn("auth.Authenticate{}", routes)
|
||||
self.assertIn("appmiddleware.Operator{}", routes)
|
||||
self.assertIn('operator.Post("/incidents/{scope}/{target}/proposals"', routes)
|
||||
self.assertIn('operator.Post("/proposals/{proposal}/approval"', routes)
|
||||
self.assertIn('operator.Get("/executions/{execution}"', routes)
|
||||
|
||||
proposal_handler = (ROOT / "apps/opsproof/overlay/handlers/proposal/proposal.go").read_text(
|
||||
encoding="utf-8"
|
||||
)
|
||||
self.assertIn("EvidenceFingerprint", proposal_handler)
|
||||
self.assertIn("CommandAllowed", proposal_handler)
|
||||
self.assertIn("LockForUpdate", proposal_handler)
|
||||
self.assertIn('arguments[2] != "--ai"', proposal_handler)
|
||||
|
||||
migration = (
|
||||
ROOT
|
||||
/ "apps/opsproof/overlay/database/migrations/2026_12_04_000003_create_opsproof_workflow_tables.go"
|
||||
).read_text(encoding="utf-8")
|
||||
self.assertIn('"remediation_proposals"', migration)
|
||||
self.assertIn('"remediation_approvals"', migration)
|
||||
self.assertIn('"operation_executions"', migration)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
Loading…
Reference in New Issue