Add OpsProof Dex operator login

This commit is contained in:
juvenal.diaz 2026-12-04 16:16:13 -06:00
parent 5a49552694
commit f015f2881e
12 changed files with 367 additions and 10 deletions

View File

@ -71,6 +71,14 @@ and the absence of a target-specific rollback. A proposal stays blocked and
cannot be approved or executed until later slices add identity, authorization,
current-evidence validation, and a validated rollback.
Operator mode uses a dedicated Dex OAuth client through Laravel Go's social
provider support. The authorization-code flow uses PKCE and server-side
sessions. Only verified identities in `LAB_OPSPROOF_OPERATOR_EMAILS` may sign
in; when the variable is omitted, the pipeline defaults to the committed Dex
user identity. Incident and future mutation routes require both authentication
and current membership in that allowlist. The overview remains a read-only
landing page.
## Security boundary
OpsProof is not a shell console.
@ -97,7 +105,7 @@ Each slice should be a small, independently testable commit:
applications);
5. remediation proposal with risk and rollback details (implemented as a
blocked, non-executable proposal);
6. Dex login and operator authorization;
6. Dex login and operator authorization (implemented);
7. approval-gated execution and live progress;
8. post-change validation and incident report;
9. sanitized public demo mode and portfolio link.

View File

@ -0,0 +1,80 @@
package bootstrap
import (
"os"
"strings"
laravel "go.laravel.com"
"go.laravel.com/auth"
"go.laravel.com/auth/social"
"go.laravel.com/config"
"go.laravel.com/db"
"go.laravel.com/db/postgres"
"go.laravel.com/inertia"
"go.laravel.com/web"
"app/commands"
"app/database/migrations"
"app/database/schema"
"app/database/seeders"
"app/jobs"
"app/listeners"
"app/models"
"app/resources"
"app/routes"
"app/services"
)
const dexProvider social.Provider = "dex"
func Options() laravel.Options {
issuer := strings.TrimRight(os.Getenv("OPSPROOF_DEX_ISSUER"), "/")
return laravel.Options{
Routes: laravel.Routes{
Web: routes.Web,
API: routes.API,
Channels: routes.Channels,
Health: "/up",
},
Middleware: func(m *laravel.Middleware, cfg *config.Config) {
m.Web.Append(auth.Session[models.User]{})
m.Web.Append(inertia.Middleware{Share: share, ErrorPage: "Error"})
},
Views: resources.Views,
Drivers: []db.Driver{postgres.Driver},
Migrations: migrations.All,
Schema: schema.Dumps,
Seeders: seeders.All,
Commands: commands.All,
Schedule: commands.Schedule,
Listeners: listeners.All,
Jobs: jobs.All,
SocialProviders: map[social.Provider]social.OAuth2{
dexProvider: {
AuthorizeURL: issuer + "/auth",
TokenURL: issuer + "/token",
Scopes: []string{"openid", "profile", "email"},
ClientID: "opsproof",
ClientSecret: os.Getenv("OPSPROOF_DEX_CLIENT_SECRET"),
RedirectURI: os.Getenv("OPSPROOF_DEX_REDIRECT_URL"),
User: social.UserInfo(issuer + "/userinfo"),
},
},
Services: laravel.BuildServices(services.New),
}
}
func share(r *web.Request) (inertia.Props, error) {
operator := inertia.Props{"authenticated": false}
if user := models.CurrentUser(r); user != nil {
operator = inertia.Props{"authenticated": true, "name": user.Name, "email": user.Email, "role": "operator"}
}
return inertia.Props{
"name": config.From(r).App.Name,
"status": r.Session().Get("status"),
"operator": operator,
}, nil
}

View File

@ -0,0 +1,75 @@
package authentication
import (
"crypto/rand"
"encoding/hex"
"net/http"
"os"
"strings"
"time"
"go.laravel.com/auth"
"go.laravel.com/auth/social"
"go.laravel.com/db"
"go.laravel.com/model"
"go.laravel.com/web"
"app/models"
)
const dexProvider social.Provider = "dex"
func Login(request *web.Request) *web.Response {
return social.Redirect(request, dexProvider)
}
func Callback(request *web.Request) *web.Response {
profile, err := social.User(request, dexProvider)
if err != nil {
return web.Fail(err)
}
email := strings.ToLower(strings.TrimSpace(profile.VerifiedEmail()))
if email == "" || !operatorAllowed(email) {
return web.Abort(http.StatusForbidden)
}
name := strings.TrimSpace(profile.Name)
if name == "" {
name = email
}
verified := time.Now().UTC()
password := make([]byte, 32)
if _, err := rand.Read(password); err != nil {
return web.Fail(err)
}
user, _, err := model.FirstOrCreate[models.User](request,
db.Values{"email": email},
db.Values{
"name": name,
"email_verified_at": verified,
"password": "dex-only-" + hex.EncodeToString(password),
},
)
if err != nil {
return web.Fail(err)
}
if err := auth.Login(request, &user, false); err != nil {
return web.Fail(err)
}
return auth.RedirectIntended("/")
}
func Logout(request *web.Request) *web.Response {
if err := auth.Logout(request); err != nil {
return web.Fail(err)
}
return web.Redirect("/")
}
func operatorAllowed(email string) bool {
for _, allowed := range strings.Split(os.Getenv("OPSPROOF_OPERATOR_EMAILS"), ",") {
if strings.EqualFold(strings.TrimSpace(allowed), email) {
return true
}
}
return false
}

View File

@ -0,0 +1,26 @@
package middleware
import (
"net/http"
"os"
"strings"
"go.laravel.com/web"
"app/models"
)
type Operator struct{}
func (Operator) Handle(request *web.Request, next web.Next) *web.Response {
user := models.CurrentUser(request)
if user == nil {
return web.Abort(http.StatusUnauthorized)
}
for _, allowed := range strings.Split(os.Getenv("OPSPROOF_OPERATOR_EMAILS"), ",") {
if strings.EqualFold(strings.TrimSpace(allowed), user.Email) {
return next(request)
}
}
return web.Abort(http.StatusForbidden)
}

View File

@ -34,6 +34,12 @@ interface Incident {
interface Props {
laravelVersion: string;
operator: {
authenticated: boolean;
name?: string;
email?: string;
role?: string;
};
view: {
available: boolean;
message: string;
@ -48,7 +54,7 @@ const tone: Record<string, string> = {
skip: 'border-slate-500/20 bg-slate-500/10 text-slate-400',
};
export default function IncidentPage({ laravelVersion, view }: Props) {
export default function IncidentPage({ laravelVersion, view, operator }: Props) {
const incident = view.incident;
return (
@ -62,9 +68,12 @@ export default function IncidentPage({ laravelVersion, view }: Props) {
</a>
<p className="mt-3 font-semibold tracking-tight">OpsProof incident evidence</p>
</div>
<span className="rounded-full border border-cyan-300/30 bg-cyan-300/10 px-3 py-1.5 text-xs text-cyan-200">
Read-only investigation
</span>
<div className="text-right">
<span className="rounded-full border border-cyan-300/30 bg-cyan-300/10 px-3 py-1.5 text-xs text-cyan-200">
Authenticated operator
</span>
<p className="mt-2 text-[11px] text-slate-500">{operator.email}</p>
</div>
</header>
{!view.available ? (

View File

@ -1,6 +1,16 @@
import { router } from '@inertiajs/react';
interface Props {
laravelVersion: string;
overview: Overview;
operator: Operator;
}
interface Operator {
authenticated: boolean;
name?: string;
email?: string;
role?: string;
}
interface StatusRow {
@ -176,7 +186,7 @@ function LiveOverview({ overview }: { overview: Overview }) {
);
}
export default function Welcome({ laravelVersion, overview }: Props) {
export default function Welcome({ laravelVersion, overview, operator }: Props) {
return (
<main className="min-h-screen bg-[#071019] text-slate-100 selection:bg-cyan-300 selection:text-slate-950">
<div className="pointer-events-none fixed inset-0 bg-[radial-gradient(circle_at_15%_10%,rgba(34,211,238,0.10),transparent_25%),radial-gradient(circle_at_85%_20%,rgba(99,102,241,0.12),transparent_28%)]" />
@ -191,6 +201,19 @@ export default function Welcome({ laravelVersion, overview }: Props) {
</div>
</div>
<div className="flex items-center gap-3 text-xs">
{operator.authenticated ? (
<button
type="button"
onClick={() => router.post('/logout')}
className="rounded-full border border-white/10 px-3 py-1.5 text-slate-300 hover:border-cyan-300/40 hover:text-cyan-200"
>
{operator.name} · sign out
</button>
) : (
<a href="/login" className="rounded-full border border-cyan-300/30 px-3 py-1.5 text-cyan-200 hover:bg-cyan-300/10">
Operator sign in
</a>
)}
<span className="hidden rounded-full border border-cyan-300/30 bg-cyan-300/10 px-3 py-1.5 text-cyan-200 sm:inline">
Read-only live view
</span>

View File

@ -3,17 +3,25 @@ package routes
import (
"net/http"
"go.laravel.com/auth"
"go.laravel.com/config"
"go.laravel.com/routing"
"go.laravel.com/web"
"app/handlers/authentication"
"app/handlers/incident"
"app/handlers/welcome"
appmiddleware "app/middleware"
)
func Web(route *routing.Router, cfg *config.Config) {
route.Get("/", welcome.Show)
route.Get("/incidents/{scope}/{target}", incident.Show)
route.Get("/login", authentication.Login).Name("login")
route.Get("/auth/dex/callback", authentication.Callback)
route.Post("/logout", authentication.Logout).Middleware(auth.Authenticate{}, appmiddleware.Operator{})
operator := route.Middleware(auth.Authenticate{}, appmiddleware.Operator{})
operator.Get("/incidents/{scope}/{target}", incident.Show)
route.Fallback(func(*web.Request) *web.Response {
return web.Abort(http.StatusNotFound)

View File

@ -0,0 +1,44 @@
package feature_test
import (
"testing"
"go.laravel.com/auth/social"
"go.laravel.com/laraveltest"
"app/tests"
)
func TestDexLoginRequiresAnAllowedVerifiedOperator(t *testing.T) {
client := tests.New(t, laraveltest.Env(map[string]string{
"OPSPROOF_DEX_ISSUER": "https://auth.example.test",
"OPSPROOF_DEX_CLIENT_SECRET": "test-secret",
"OPSPROOF_OPERATOR_EMAILS": "operator@example.test",
}))
client.WithoutRedirects().Get("/incidents/cluster/n8n").AssertRedirect("/login")
allowed := client.FakeSocial("dex", &social.Profile{
ID: "dex-operator",
Name: "Homelab Operator",
Email: "operator@example.test",
EmailVerified: true,
})
allowed.WithoutRedirects().Get("/auth/dex/callback").AssertRedirect("/")
allowed.Get("/").AssertOK().AssertInertia("Welcome").AssertProp("operator.authenticated", true)
}
func TestDexLoginRejectsAnUnlistedIdentity(t *testing.T) {
client := tests.New(t, laraveltest.Env(map[string]string{
"OPSPROOF_DEX_ISSUER": "https://auth.example.test",
"OPSPROOF_DEX_CLIENT_SECRET": "test-secret",
"OPSPROOF_OPERATOR_EMAILS": "operator@example.test",
})).FakeSocial("dex", &social.Profile{
ID: "dex-other",
Name: "Other User",
Email: "other@example.test",
EmailVerified: true,
})
client.Get("/auth/dex/callback").AssertForbidden()
}

View File

@ -5,8 +5,10 @@ import (
"net/http/httptest"
"testing"
"app/models"
"app/services"
"app/tests"
"go.laravel.com/laraveltest"
)
func TestIncidentPageRendersDeterministicDoctorEvidence(t *testing.T) {
@ -23,7 +25,9 @@ func TestIncidentPageRendersDeterministicDoctorEvidence(t *testing.T) {
}))
defer server.Close()
client := tests.New(t)
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.Get("/incidents/cluster/n8n").AssertOK().AssertInertia("Incident")
}

View File

@ -61,6 +61,9 @@ confirmed by deterministic validation.
- Store the Jeannie bearer token server-side only.
- Use Dex OIDC for operator mode; never expose operator actions in public demo
mode.
- Give OpsProof its own generated Dex client secret, use authorization code
with PKCE, require a verified email, and re-check the operator allowlist on
every protected request rather than treating a past login as authorization.
- Fail closed when Jeannie is unreachable or its advertised command surface
differs from the proposal.
- Collect the overview through Jeannie's authenticated, read-only status

View File

@ -1078,8 +1078,22 @@ render_dex_config() {
local office_client_secret="${12:-}"
local argocd_public_url="${13:-}"
local argocd_client_secret="${14:-}"
local opsproof_public_url="${15:-}"
local opsproof_client_secret="${16:-}"
local office_client_block=""
local argocd_client_block=""
local opsproof_client_block=""
if [[ -n "${opsproof_public_url}" && -n "${opsproof_client_secret}" ]]; then
opsproof_client_block="$(cat <<OPSPROOF_CLIENT_EOF
- id: opsproof
name: OpsProof
secret: "${opsproof_client_secret}"
redirectURIs:
- ${opsproof_public_url%/}/auth/dex/callback
OPSPROOF_CLIENT_EOF
)"
fi
if [[ -n "${argocd_public_url}" && -n "${argocd_client_secret}" ]]; then
argocd_client_block="$(cat <<ARGOCD_CLIENT_EOF
@ -1137,6 +1151,7 @@ staticClients:
- ${gitea_public_url}/user/oauth2/${gitea_source_name}/callback
${office_client_block}
${argocd_client_block}
${opsproof_client_block}
staticPasswords:
- email: "${user_email}"
@ -1169,6 +1184,9 @@ deploy_dex() {
local dex_uid="${LAB_DEX_CONTAINER_UID:-1001}"
local dex_gid="${LAB_DEX_CONTAINER_GID:-1001}"
local elapsed=0
local opsproof_oidc_env="${LAB_OPSPROOF_INSTALL_DIR:-/data/homelab-opsproof}/.oidc.env"
local opsproof_public_url=""
local opsproof_client_secret=""
require_debian_server "deploy-dex"
@ -1202,6 +1220,10 @@ deploy_dex() {
dex_env="$(dex_secret_values)" || exit 1
eval "${dex_env}"
office_client_secret="${office_client_secret:-${DEX_OFFICE_CLIENT_SECRET:-}}"
if [[ -r "${opsproof_oidc_env}" ]]; then
opsproof_public_url="$(sed -n 's/^OPSPROOF_PUBLIC_URL=//p' "${opsproof_oidc_env}" | head -n 1)"
opsproof_client_secret="$(sed -n 's/^OPSPROOF_DEX_CLIENT_SECRET=//p' "${opsproof_oidc_env}" | head -n 1)"
fi
echo "Deploying Dex on the Debian host at ${install_dir}..."
@ -1231,7 +1253,9 @@ deploy_dex() {
"${office_public_url}" \
"${office_client_secret}" \
"${LAB_ARGOCD_PUBLIC_URL:-https://argocd.${LAB_DOMAIN:-lab2025.duckdns.org}}" \
"${DEX_ARGOCD_CLIENT_SECRET:-}" |
"${DEX_ARGOCD_CLIENT_SECRET:-}" \
"${opsproof_public_url}" \
"${opsproof_client_secret}" |
sudo tee "${install_dir}/config.yaml" >/dev/null
sudo chown "${dex_uid}:${dex_gid}" "${install_dir}/config.yaml"
sudo chown -R "${dex_uid}:${dex_gid}" "${data_dir}"
@ -5694,6 +5718,11 @@ deploy_opsproof() {
local postgres_uid=""
local postgres_gid=""
local database_url=""
local oidc_env="${install_dir}/.oidc.env"
local oidc_secret=""
local public_url="${LAB_OPSPROOF_PUBLIC_URL:-http://${bind_ip}:${http_port}}"
local operator_emails="${LAB_OPSPROOF_OPERATOR_EMAILS:-}"
local opsproof_dex_values=""
local elapsed=0
local node_major=""
local required
@ -5739,6 +5768,19 @@ deploy_opsproof() {
echo "LAB_OPSPROOF_JEANNIE_URL must be an HTTP or HTTPS URL." >&2
return 1
fi
if ! [[ "${public_url}" =~ ^https?://[^[:space:]]+$ ]]; then
echo "LAB_OPSPROOF_PUBLIC_URL must be an HTTP or HTTPS URL." >&2
return 1
fi
if [[ -z "${operator_emails}" ]]; then
opsproof_dex_values="$(dex_secret_values)" || return 1
eval "${opsproof_dex_values}"
operator_emails="${DEX_USER_EMAIL:-}"
fi
if [[ -z "${operator_emails}" || "${operator_emails}" == *[[:space:]]* ]]; then
echo "LAB_OPSPROOF_OPERATOR_EMAILS must contain a comma-separated operator email allowlist without spaces." >&2
return 1
fi
if [[ -z "${jeannie_api_token}" || "${jeannie_api_token}" == *[[:space:]]* ]]; then
echo "OpsProof requires the Jeannie API token through LAB_OPSPROOF_JEANNIE_TOKEN, JEANNIE_SERVER_TOKEN, or ${jeannie_api_env}." >&2
return 1
@ -5762,6 +5804,21 @@ deploy_opsproof() {
sudo install -d -o "${service_user}" -g "${service_user}" -m 0750 \
"${install_dir}" "${install_dir}/releases" "${install_dir}/toolchains"
if [[ -s "${oidc_env}" ]]; then
oidc_secret="$(sed -n 's/^OPSPROOF_DEX_CLIENT_SECRET=//p' "${oidc_env}" | head -n 1)"
fi
if ! [[ "${oidc_secret}" =~ ^[[:xdigit:]]{64}$ ]]; then
oidc_secret="$(openssl rand -hex 32)"
fi
umask 077
printf '%s\n' \
"OPSPROOF_PUBLIC_URL=${public_url%/}" \
"OPSPROOF_DEX_CLIENT_SECRET=${oidc_secret}" >"${oidc_env}"
chmod 0600 "${oidc_env}"
# Dex owns the OAuth client registry. Re-render it from the committed
# encrypted source plus this private generated client secret.
deploy_dex
sudo install -d -m 0700 "${install_dir}/postgres"
if ! sudo docker image inspect "${postgres_image}" >/dev/null 2>&1; then
@ -5879,12 +5936,16 @@ COMPOSE_EOF
"APP_ENV=production" \
"APP_KEY=${app_key}" \
"APP_DEBUG=false" \
"APP_URL=http://${bind_ip}:${http_port}" \
"APP_URL=${public_url%/}" \
"SERVER_HOST=${bind_ip}" \
"SERVER_PORT=${http_port}" \
"DATABASE_URL=${database_url}" \
"OPSPROOF_JEANNIE_URL=${jeannie_api_url}" \
"OPSPROOF_JEANNIE_TOKEN=${jeannie_api_token}" \
"OPSPROOF_DEX_ISSUER=$(dex_public_url | sed 's:/*$::')" \
"OPSPROOF_DEX_CLIENT_SECRET=${oidc_secret}" \
"OPSPROOF_DEX_REDIRECT_URL=${public_url%/}/auth/dex/callback" \
"OPSPROOF_OPERATOR_EMAILS=${operator_emails}" \
"SESSION_DRIVER=memory" \
"CACHE_STORE=memory" \
"QUEUE_CONNECTION=sync" \

View File

@ -70,6 +70,8 @@ class OpsProofPipelineTests(unittest.TestCase):
self.assertNotIn('"CACHE_STORE=file"', pipeline)
self.assertIn('"OPSPROOF_JEANNIE_URL=${jeannie_api_url}"', pipeline)
self.assertIn('"OPSPROOF_JEANNIE_TOKEN=${jeannie_api_token}"', pipeline)
self.assertIn('"OPSPROOF_DEX_CLIENT_SECRET=${oidc_secret}"', pipeline)
self.assertIn('"OPSPROOF_OPERATOR_EMAILS=${operator_emails}"', pipeline)
self.assertIn("JEANNIE_SERVER_TOKEN=//p", pipeline)
self.assertIn('"${release_dir}/opsproof" migrate --force', pipeline)
self.assertIn(
@ -135,6 +137,20 @@ class OpsProofPipelineTests(unittest.TestCase):
self.assertIn('proposal.Status = "blocked"', client)
self.assertIn('"./jeannie doctor cluster " + incident.Target + " --ai"', client)
auth_handler = (
ROOT / "apps/opsproof/overlay/handlers/authentication/authentication.go"
).read_text(encoding="utf-8")
self.assertIn("profile.VerifiedEmail()", auth_handler)
self.assertIn("operatorAllowed(email)", auth_handler)
self.assertIn("auth.Login", auth_handler)
routes = (ROOT / "apps/opsproof/overlay/routes/web.go").read_text(
encoding="utf-8"
)
self.assertIn('route.Get("/login"', routes)
self.assertIn("auth.Authenticate{}", routes)
self.assertIn("appmiddleware.Operator{}", routes)
if __name__ == "__main__":
unittest.main()