SPB Git

Repository Public

ConnectPage.swift 40.3 KB 670 lines swift

1// Connect & Agents: managed secrets that services and AI agents may use through SP Vault.2//3// DIFFERENT TRUST MODEL — stated on the page and in every creation form: managed secrets are NOT zero-knowledge.4// The server can decrypt them, because it uses them on the owner's behalf (services/managed-secrets/THREAT_MODEL.md).5// The personal vault is never involved. Text supplied by an agent is always shown boxed and labelled as untrusted.6import SharedVaultKit7import SwiftUI89private let connectBanner = "Managed secrets are NOT zero-knowledge: this server can decrypt them so it can use them on your behalf. Never move personal passwords here."1011struct ConnectPage: View {12    @Environment(AppModel.self) private var model13    @State private var data: ConnectOverview?14    @State private var error: String?15    @State private var confirm: ConfirmRequest?16    @State private var sheet: Sheet?1718    enum Sheet: Identifiable {19        case secret, identity, grant, rotate(ManagedSecretInfo)20        var id: String {21            switch self {22            case .secret: "secret"23            case .identity: "identity"24            case .grant: "grant"25            case .rotate(let s): "rotate-\(s.id)"26            }27        }28    }2930    private var pending: [ConnectApproval] { (data?.approvals ?? []).filter { $0.status == "pending" } }3132    var body: some View {33        ToolPage("Connect & Agents", subtitle: "Let services and AI agents use specific credentials without ever touching your personal vault.") {34            Button { Task { await load() } } label: { Label("Refresh", systemImage: "arrow.clockwise") }35                .buttonStyle(.vaultCompact).accessibilityIdentifier("connect-refresh")36        } content: {37            Callout(kind: .danger, title: "Different trust model — not zero-knowledge", text: connectBanner).accessibilityIdentifier("connect-banner")38            ErrorText(text: error)39            if let data {40                if !data.enabled {41                    VStack(spacing: 0) {42                        EmptyState(symbol: "cpu", title: "Connect is not enabled on this server",43                                   text: "The managed-secrets service is a separate, isolated process that the operator has not switched on. Your personal vault is unaffected; nothing here is required to use SP Vault.")44                    }45                    .frame(minHeight: 240).accessibilityIdentifier("connect-disabled")46                } else {47                    killSwitch(data)48                    approvals49                    secrets(data)50                    identities(data)51                    grants(data)52                }53            } else if error == nil {54                HStack(spacing: 10) { ProgressView(); Text("Loading…").foregroundStyle(Palette.muted) }55            }56        }57        .task(id: model.approvalsTick) { await load() }58        .confirmSheet($confirm)59        .sheet(item: $sheet) { s in60            Group {61                switch s {62                case .secret: NewManagedSecretSheet { await load() }63                case .identity: NewIdentitySheet { await load() }64                case .grant: if let data { NewGrantSheet(data: data) { await load() } }65                case .rotate(let secret): RotateSecretSheet(secret: secret) { await load() }66                }67            }68            .environment(model)69        }70        .containerID("connect-page")71    }7273    private func load() async {74        guard model.isUnlocked else { return }75        do { data = try await model.engine.connect(); error = nil }76        catch { self.error = model.errorText(error) ?? self.error }77    }7879    /// Runs an engine call, toasts the result, reloads.80    private func run(_ done: String, _ op: @escaping () async throws -> Void) async {81        await model.act(done) { try await op() }82        await load()83    }8485    private func name(_ id: String, in secrets: [ManagedSecretInfo]) -> String { secrets.first { $0.id == id }?.name ?? "\(id.prefix(8))…" }86    private func name(_ id: String, in identities: [ConnectIdentity]) -> String { identities.first { $0.id == id }?.name ?? "\(id.prefix(8))…" }8788    // ── kill switch ──89    private func killSwitch(_ data: ConnectOverview) -> some View {90        HStack(alignment: .center, spacing: 14) {91            Image(systemName: "power").font(.system(size: 20, weight: .semibold)).foregroundStyle(data.killed ? Palette.danger : Palette.muted)92                .frame(width: 40, height: 40).background(data.killed ? Palette.dangerSoft : Palette.s2, in: Circle()).accessibilityHidden(true)93            VStack(alignment: .leading, spacing: 3) {94                Text(data.killed ? "Kill switch ENGAGED" : "Kill switch").font(.vaultHeadline).foregroundStyle(data.killed ? Palette.danger : Palette.text)95                Text(data.killed ? "Every service and agent identity is suspended. No managed secret can be used."96                     : "Suspends every identity at once, ends all leases and denies pending requests. One tap, no confirmation.")97                    .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)98            }99            Spacer(minLength: 8)100            if data.killed {101                Button("Release…") {102                    confirm = ConfirmRequest(title: "Release the kill switch?",103                                             message: "Identities become usable again within their grants. Leases that were ended stay ended; pending requests were denied. Releasing asks for a fresh confirmation on this device.",104                                             confirmLabel: "Release", destructive: false) {105                        await run("Kill switch released") { try await model.engine.setKillSwitch(engaged: false) }106                    }107                }108                .buttonStyle(.vaultSecondary).accessibilityIdentifier("connect-kill-release")109            } else {110                Button("Engage") { Task { await run("Kill switch engaged: every identity is suspended and all leases ended") { try await model.engine.setKillSwitch(engaged: true) } } }111                    .buttonStyle(.vaultDanger).accessibilityIdentifier("connect-kill-engage")112            }113        }114        .padding(14)115        .background(data.killed ? Palette.dangerSoft : Palette.s1, in: RoundedRectangle(cornerRadius: Metrics.radiusLarge, style: .continuous))116        .overlay(RoundedRectangle(cornerRadius: Metrics.radiusLarge, style: .continuous).strokeBorder(data.killed ? Palette.dangerLine : Palette.line, lineWidth: 1))117        .containerID("connect-kill")118    }119120    // ── approvals ──121    @ViewBuilder private var approvals: some View {122        VStack(alignment: .leading, spacing: 8) {123            Eyebrow(pending.isEmpty ? "Pending approvals" : "Pending approvals (\(pending.count))")124            if pending.isEmpty {125                Text("No request is waiting for you.").font(.callout).foregroundStyle(Palette.muted).accessibilityIdentifier("connect-approvals-empty")126            } else {127                ForEach(pending) { a in128                    ApprovalCard(approval: a) { approve in129                        await run(approve ? "Request approved" : "Request denied") { try await model.engine.decideApproval(id: a.id, approve: approve) }130                    }131                }132            }133        }134    }135136    // ── managed secrets ──137    private func secrets(_ data: ConnectOverview) -> some View {138        SectionCard("Managed secrets") {139            Button { sheet = .secret } label: { Label("New secret", systemImage: "plus") }.buttonStyle(.vaultCompact).accessibilityIdentifier("connect-secret-new")140        } content: {141            if data.secrets.isEmpty {142                CardRow(last: true) { Text("No managed secret. Create one for an API credential that a workload should use.").font(.callout).foregroundStyle(Palette.muted) }143            }144            ForEach(Array(data.secrets.enumerated()), id: \.element.id) { i, s in145                CardRow(last: i == data.secrets.count - 1) {146                    HStack(alignment: .center, spacing: 10) {147                        VStack(alignment: .leading, spacing: 4) {148                            HStack(spacing: 8) {149                                Text(s.name).font(.body.weight(.semibold)).foregroundStyle(Palette.text)150                                Pill(text: ConnectKinds.label(s.kind))151                                Pill(text: "v\(s.version)")152                            }153                            Text(secretDetail(s)).font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)154                        }155                        Spacer(minLength: 8)156                        Button("Rotate") { sheet = .rotate(s) }.buttonStyle(.vaultCompact).accessibilityIdentifier("connect-secret-rotate").accessibilityLabel("Rotate \(s.name)")157                        IconButton(systemName: "trash", label: "Delete \(s.name)", tint: Palette.danger) {158                            confirm = ConfirmRequest(title: "Delete “\(s.name)”?", message: "The stored value is erased from the server and every grant and lease on it ends. This cannot be undone.", confirmLabel: "Delete secret") {159                                await run("Managed secret deleted") { try await model.engine.deleteManagedSecret(id: s.id) }160                            }161                        }162                        .accessibilityIdentifier("connect-secret-delete")163                    }164                    .containerID("connect-secret-row")165                }166            }167        }168    }169170    private func secretDetail(_ s: ManagedSecretInfo) -> String {171        var parts: [String] = []172        let hosts = (s.config["allowedHosts"]?.arrayValue ?? []).compactMap(\.stringValue)173        if !hosts.isEmpty { parts.append("only sent to \(hosts.joined(separator: ", "))") }174        let methods = (s.config["allowedMethods"]?.arrayValue ?? []).compactMap(\.stringValue)175        if !methods.isEmpty { parts.append(methods.joined(separator: " ")) }176        parts.append(s.rotatedAt != nil ? "rotated \(ItemMeta.relative(s.rotatedAt))" : "created \(ItemMeta.relative(s.createdAt))")177        if let d = s.rotateEveryDays { parts.append("rotate every \(d) days") }178        if let e = s.expiresAt { parts.append("expires \(ItemMeta.date(e))") }179        return parts.joined(separator: " · ")180    }181182    // ── identities ──183    private func identities(_ data: ConnectOverview) -> some View {184        SectionCard("Identities", footer: "An identity is a service or an agent with its own signing key. It can do nothing until you create a grant for it.") {185            Button { sheet = .identity } label: { Label("New identity", systemImage: "plus") }.buttonStyle(.vaultCompact).accessibilityIdentifier("connect-identity-new")186        } content: {187            if data.identities.isEmpty {188                CardRow(last: true) { Text("No workload identity yet.").font(.callout).foregroundStyle(Palette.muted) }189            }190            ForEach(Array(data.identities.enumerated()), id: \.element.id) { i, ident in191                CardRow(last: i == data.identities.count - 1) {192                    HStack(alignment: .center, spacing: 10) {193                        VStack(alignment: .leading, spacing: 4) {194                            HStack(spacing: 8) {195                                Text(ident.name).font(.body.weight(.semibold)).foregroundStyle(Palette.text)196                                Pill(text: ident.kind, tint: ident.kind == "agent" ? Palette.brass : Palette.muted)197                                if ident.revoked { Pill(text: "revoked", tint: Palette.danger) }198                            }199                            Text("\(ident.id.prefix(8))… · created \(ItemMeta.relative(ident.createdAt)) · last used \(ItemMeta.relative(ident.lastUsedAt))")200                                .font(.caption).foregroundStyle(Palette.muted)201                        }202                        Spacer(minLength: 8)203                        if !ident.revoked {204                            Button("Revoke") {205                                confirm = ConfirmRequest(title: "Revoke “\(ident.name)”?", message: "Its key stops being accepted at once and its leases end. Grants for it become useless. This cannot be undone.", confirmLabel: "Revoke identity") {206                                    await run("Identity revoked") { try await model.engine.revokeIdentity(id: ident.id) }207                                }208                            }209                            .buttonStyle(.vaultDangerGhost).accessibilityIdentifier("connect-identity-revoke").accessibilityLabel("Revoke \(ident.name)")210                        }211                    }212                    .containerID("connect-identity-row")213                }214            }215        }216    }217218    // ── grants ──219    private func grants(_ data: ConnectOverview) -> some View {220        SectionCard("Grants", footer: "A grant lets one identity use one secret. “Operate” keeps the secret inside SP Vault; “read” hands the raw secret to the workload, which can then disclose it.") {221            Button { sheet = .grant } label: { Label("New grant", systemImage: "plus") }.buttonStyle(.vaultCompact)222                .disabled(data.secrets.isEmpty || !data.identities.contains { !$0.revoked }).accessibilityIdentifier("connect-grant-new")223        } content: {224            if data.grants.isEmpty { CardRow(last: true) { Text("No grant.").font(.callout).foregroundStyle(Palette.muted) } }225            ForEach(Array(data.grants.enumerated()), id: \.element.id) { i, g in226                let expired = (ItemMeta.parseISO(g.expiresAt) ?? .distantFuture) < Date()227                CardRow(last: i == data.grants.count - 1) {228                    HStack(alignment: .center, spacing: 10) {229                        VStack(alignment: .leading, spacing: 5) {230                            HStack(spacing: 8) {231                                Text("\(name(g.identityId, in: data.identities)) → \(name(g.secretId, in: data.secrets))").font(.body.weight(.semibold)).foregroundStyle(Palette.text)232                                if g.revoked { Pill(text: "revoked", tint: Palette.danger) } else if expired { Pill(text: "expired") } else { Pill(text: "active", tint: Palette.accent) }233                            }234                            ViewThatFits(in: .horizontal) {235                                HStack(spacing: 6) { grantPills(g) }236                                VStack(alignment: .leading, spacing: 4) { grantPills(g) }237                            }238                            Text("\(expired ? "Expired" : "Expires") \(ItemMeta.date(g.expiresAt))").font(.caption).foregroundStyle(Palette.muted)239                        }240                        Spacer(minLength: 8)241                        if !g.revoked && !expired {242                            Button("Revoke") { Task { await run("Grant revoked") { try await model.engine.revokeGrant(id: g.id) } } }243                                .buttonStyle(.vaultDangerGhost).accessibilityIdentifier("connect-grant-revoke")244                        }245                    }246                    .containerID("connect-grant-row")247                }248            }249        }250    }251252    @ViewBuilder private func grantPills(_ g: ConnectGrant) -> some View {253        Pill(text: g.mode, tint: g.mode == "read" ? Palette.danger : Palette.accent)254        Pill(text: "approval: \(g.approval)")255        if g.approval == "lease" { Pill(text: "lease \(max(1, g.leaseTtlSec / 60)) min") }256        Pill(text: "\(g.uses)\(g.maxUses.map { " / \($0)" } ?? "") uses")257        let methods = (g.constraints["methods"]?.arrayValue ?? []).compactMap(\.stringValue)258        if !methods.isEmpty { Pill(text: methods.joined(separator: " ")) }259        if let p = g.constraints["pathPrefix"]?.stringValue, !p.isEmpty { Pill(text: "path \(p.prefix(24))") }260    }261}262263enum ConnectKinds {264    static let all: [(id: String, label: String)] = [("http-bearer", "HTTP bearer token"), ("http-header", "HTTP custom header"), ("http-basic", "HTTP basic auth"), ("hmac", "HMAC signing key"), ("raw", "Raw secret")]265    static func label(_ id: String) -> String { all.first { $0.id == id }?.label ?? id }266    static let methods = ["GET", "POST", "PUT", "PATCH", "DELETE"]267}268269// ── one pending approval ──270271private struct ApprovalCard: View {272    let approval: ConnectApproval273    let decide: (Bool) async -> Void274    @State private var busy = false275276    private func text(_ k: String) -> String? { approval.summary[k]?.stringValue.map { String($0.prefix(300)) } }277278    var body: some View {279        let s = approval.summary280        let op = text("op")281        VStack(alignment: .leading, spacing: 10) {282            HStack(spacing: 8) {283                Image(systemName: "cpu").foregroundStyle(Palette.brass).accessibilityHidden(true)284                Text(text("identity") ?? "Unknown identity").font(.body.weight(.semibold)).foregroundStyle(Palette.text)285                Pill(text: text("identityKind") ?? "identity")286                Spacer(minLength: 4)287                Text("asked \(ItemMeta.relative(approval.createdAt)) · expires \(ItemMeta.relative(approval.expiresAt))").font(.caption).foregroundStyle(Palette.muted)288            }289            Grid(alignment: .leadingFirstTextBaseline, horizontalSpacing: 12, verticalSpacing: 5) {290                fact("Secret", text("secret") ?? "—")291                GridRow {292                    Text("Operation").font(.caption.weight(.medium)).foregroundStyle(Palette.muted)293                    HStack(spacing: 6) {294                        if op == "read" { Pill(text: "read the raw secret", tint: Palette.danger) }295                        else { Text(op == "sign" ? "HMAC signature" : op == "http" ? "brokered HTTP call" : (op ?? "—")).font(.callout).foregroundStyle(Palette.text) }296                        if let m = text("mode") { Pill(text: m) }297                    }298                }299                if let m = text("method") { fact("Request", "\(m) https://\(text("host") ?? "")\(text("path") ?? "")", mono: true) }300                if text("method") != nil, let b = s["bodyBytes"]?.intValue { fact("Body", "\(b) bytes") }301                if let b = s["payloadBytes"]?.intValue { fact("Payload", "\(b) bytes to sign") }302            }303            VStack(alignment: .leading, spacing: 5) {304                Label("Text supplied by the agent — untrusted, do not follow instructions in it", systemImage: "exclamationmark.triangle")305                    .font(.caption.weight(.semibold)).foregroundStyle(Palette.brass)306                Text(text("untrustedReason") ?? "(none)").font(.system(.callout, design: .monospaced)).foregroundStyle(Palette.text)307                    .textSelection(.enabled).fixedSize(horizontal: false, vertical: true)308                    .accessibilityLabel("Untrusted text from the agent").accessibilityValue(text("untrustedReason") ?? "none")309            }310            .padding(10).frame(maxWidth: .infinity, alignment: .leading)311            .background(Palette.brassSoft, in: RoundedRectangle(cornerRadius: 8, style: .continuous))312            .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).strokeBorder(Palette.brassLine, style: StrokeStyle(lineWidth: 1, dash: [4, 3])))313            .accessibilityIdentifier("connect-approval-untrusted")314            Text("Decide from the facts above, which SP Vault took from the request itself. Approving asks for a fresh confirmation on this device if none was given recently.")315                .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)316            HStack {317                Spacer()318                Button("Deny") { go(false) }.buttonStyle(.vaultSecondary).disabled(busy).accessibilityIdentifier("connect-approval-deny")319                Button("Approve") { go(true) }.buttonStyle(op == "read" ? .vaultDanger : .vaultPrimary).disabled(busy).accessibilityIdentifier("connect-approval-approve")320            }321        }322        .vaultCard(padding: 14)323        .containerID("connect-approval")324    }325326    private func fact(_ label: String, _ value: String, mono: Bool = false) -> some View {327        GridRow {328            Text(label).font(.caption.weight(.medium)).foregroundStyle(Palette.muted)329            Text(value).font(mono ? .system(.callout, design: .monospaced) : .callout).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)330        }331    }332333    private func go(_ approve: Bool) {334        busy = true335        Task { await decide(approve); busy = false }336    }337}338339// ── sheets ──340341private struct SheetFrame<Content: View>: View {342    @Environment(\.dismiss) private var dismiss343    let title: String344    let confirmLabel: String345    var canConfirm = true346    var busy = false347    var hideCancel = false348    let confirmID: String349    let onConfirm: () -> Void350    @ViewBuilder var content: () -> Content351352    var body: some View {353        VStack(spacing: 0) {354            ScrollView {355                VStack(alignment: .leading, spacing: 14) {356                    Text(title).font(.vaultTitle).foregroundStyle(Palette.text).accessibilityAddTraits(.isHeader)357                    content()358                }359                .padding(22).frame(maxWidth: .infinity, alignment: .leading)360            }361            Rectangle().fill(Palette.line).frame(height: 1)362            HStack {363                Spacer()364                if !hideCancel { Button("Cancel") { dismiss() }.buttonStyle(.vaultSecondary).keyboardShortcut(.cancelAction).accessibilityIdentifier("connect-sheet-cancel") }365                Button(busy ? "Working…" : confirmLabel, action: onConfirm).buttonStyle(.vaultPrimary).disabled(!canConfirm || busy).accessibilityIdentifier(confirmID)366            }367            .padding(.horizontal, 22).padding(.vertical, 12)368        }369        .background(Palette.s1)370        #if os(macOS)371        .frame(width: 520).frame(minHeight: 320, maxHeight: 640)372        #endif373    }374}375376private struct MethodChecks: View {377    let label: String378    @Binding var selection: Set<String>379    var body: some View {380        HStack(spacing: 6) {381            ForEach(ConnectKinds.methods, id: \.self) { m in382                let on = selection.contains(m)383                Button { if on { selection.remove(m) } else { selection.insert(m) } } label: {384                    Text(m).font(.caption.monospaced().weight(.semibold)).foregroundStyle(on ? Palette.accentInk : Palette.muted)385                        .padding(.horizontal, 9).padding(.vertical, 6)386                        .background(on ? Palette.accent : Palette.s2, in: RoundedRectangle(cornerRadius: 7, style: .continuous))387                        .overlay(RoundedRectangle(cornerRadius: 7, style: .continuous).strokeBorder(on ? Color.clear : Palette.lineStrong, lineWidth: 1))388                }389                .buttonStyle(.plain)390                .accessibilityLabel("\(label): \(m)").accessibilityAddTraits(on ? .isSelected : [])391            }392        }393    }394}395396private struct NewManagedSecretSheet: View {397    @Environment(AppModel.self) private var model398    @Environment(\.dismiss) private var dismiss399    let onDone: () async -> Void400    @State private var name = ""401    @State private var kind = "http-bearer"402    @State private var hosts = ""403    @State private var methods: Set<String> = ["GET", "POST"]404    @State private var header = ""405    @State private var prefix = ""406    @State private var username = ""407    @State private var value = ""408    @State private var rotate = ""409    @State private var ack = false410    @State private var error: String?411412    private var http: Bool { kind.hasPrefix("http-") }413    private var hostList: [String] { hosts.split(whereSeparator: { $0 == "," || $0.isWhitespace }).map { $0.lowercased() }.filter { !$0.isEmpty } }414    private var ready: Bool {415        !name.trimmingCharacters(in: .whitespaces).isEmpty && !value.isEmpty && ack && (!http || !hostList.isEmpty) && (kind != "http-header" || !header.trimmingCharacters(in: .whitespaces).isEmpty)416    }417418    var body: some View {419        SheetFrame(title: "New managed secret", confirmLabel: "Create", canConfirm: ready, busy: model.busy, confirmID: "connect-secret-create", onConfirm: create) {420            Callout(kind: .danger, title: "Not zero-knowledge", text: connectBanner)421            LabeledField(label: "Name") { TextField("", text: $name).textFieldStyle(.vault).accessibilityIdentifier("connect-secret-name").accessibilityLabel("Name") }422            LabeledField(label: "Kind") {423                Picker("Kind", selection: $kind) { ForEach(ConnectKinds.all, id: \.id) { Text($0.label).tag($0.id) } }424                    .labelsHidden().accessibilityIdentifier("connect-secret-kind")425            }426            if http {427                LabeledField(label: "Allowed hosts", hint: "Comma-separated. The credential is only ever sent to these hosts (use *.example.com for subdomains).") {428                    TextField("api.example.com", text: $hosts).textFieldStyle(.vaultMono).rawTextInput().accessibilityIdentifier("connect-secret-hosts").accessibilityLabel("Allowed hosts")429                }430                LabeledField(label: "Allowed methods") { MethodChecks(label: "Allowed method", selection: $methods) }431            }432            if kind == "http-header" {433                LabeledField(label: "Header name") { TextField("X-Api-Key", text: $header).textFieldStyle(.vaultMono).rawTextInput().accessibilityLabel("Header name") }434                LabeledField(label: "Value prefix (optional)") { TextField("", text: $prefix).textFieldStyle(.vaultMono).rawTextInput().accessibilityLabel("Value prefix") }435            }436            if kind == "http-bearer" {437                LabeledField(label: "Prefix (optional)", hint: "Defaults to “Bearer ”.") { TextField("", text: $prefix).textFieldStyle(.vaultMono).rawTextInput().accessibilityLabel("Prefix") }438            }439            if kind == "http-basic" {440                LabeledField(label: "Username") { TextField("", text: $username).textFieldStyle(.vault).rawTextInput().accessibilityLabel("Username") }441            }442            LabeledField(label: "Secret value", hint: "Sent to the server over TLS and stored encrypted under a key the server holds.") {443                SecureField("", text: $value).textFieldStyle(.vaultMono).accessibilityIdentifier("connect-secret-value").accessibilityLabel("Secret value")444            }445            LabeledField(label: "Rotation reminder (days, optional)") {446                TextField("", text: $rotate).textFieldStyle(.vault).rawTextInput().frame(maxWidth: 120).accessibilityLabel("Rotation reminder in days")447            }448            Toggle(isOn: $ack) {449                Text("I understand that the server can read this secret, and that it is not one of my personal passwords.").font(.callout).foregroundStyle(Palette.text).fixedSize(horizontal: false, vertical: true)450            }451            .accessibilityIdentifier("connect-secret-ack")452            ErrorText(text: error)453        }454    }455456    private func create() {457        var config = JSONObject()458        if http {459            config["allowedHosts"] = .array(hostList.map { .string($0) })460            config["allowedMethods"] = .array(ConnectKinds.methods.filter(methods.contains).map { .string($0) })461        }462        if kind == "http-header" { config["header"] = .string(header.trimmingCharacters(in: .whitespaces)); if !prefix.isEmpty { config["prefix"] = .string(prefix) } }463        if kind == "http-bearer", !prefix.isEmpty { config["prefix"] = .string(prefix) }464        if kind == "http-basic", !username.isEmpty { config["username"] = .string(username) }465        let days = Int(rotate.trimmingCharacters(in: .whitespaces)) ?? 0466        let secret = NewManagedSecret(name: name.trimmingCharacters(in: .whitespaces), kind: kind, config: .object(config), value: value, rotateEveryDays: (1...3650).contains(days) ? days : nil)467        Task {468            error = await model.perform("Managed secret created") { try await model.engine.createManagedSecret(secret) }469            if error == nil { value = ""; await onDone(); dismiss() }470        }471    }472}473474private struct RotateSecretSheet: View {475    @Environment(AppModel.self) private var model476    @Environment(\.dismiss) private var dismiss477    let secret: ManagedSecretInfo478    let onDone: () async -> Void479    @State private var value = ""480    @State private var error: String?481482    var body: some View {483        SheetFrame(title: "Rotate “\(secret.name)”", confirmLabel: "Replace value", canConfirm: !value.isEmpty, busy: model.busy, confirmID: "connect-rotate-confirm", onConfirm: go) {484            Text("The new value replaces version \(secret.version). Every active lease on this secret ends immediately; grants stay in place.")485                .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)486            LabeledField(label: "New value", hint: "Sent to the server over TLS and stored encrypted under a key the server holds.") {487                SecureField("", text: $value).textFieldStyle(.vaultMono).accessibilityIdentifier("connect-rotate-value").accessibilityLabel("New value")488            }489            ErrorText(text: error)490        }491    }492493    private func go() {494        let v = value495        Task {496            error = await model.perform("Managed secret rotated") { try await model.engine.rotateManagedSecret(id: secret.id, value: v) }497            if error == nil { value = ""; await onDone(); dismiss() }498        }499    }500}501502private struct NewIdentitySheet: View {503    @Environment(AppModel.self) private var model504    @Environment(\.dismiss) private var dismiss505    let onDone: () async -> Void506    @State private var name = ""507    @State private var kind = "agent"508    @State private var error: String?509    @State private var created: WorkloadIdentitySecret?510    @State private var revealed = false511512    var body: some View {513        if let created {514            SheetFrame(title: "Identity created", confirmLabel: "I stored the key — done", hideCancel: true, confirmID: "connect-identity-done", onConfirm: { self.created = nil; dismiss() }) {515                Callout(kind: .warn, title: "The private key is shown once",516                        text: "It was generated on this device; the server only received the public key. Store it in the workload's secret store now — it cannot be displayed again.")517                LabeledField(label: "Identity ID") {518                    HStack {519                        Text(created.id).font(.secret).foregroundStyle(Palette.text).textSelection(.enabled).lineLimit(2).accessibilityIdentifier("connect-identity-id")520                        Spacer(minLength: 6)521                        Button("Copy") { model.copy(created.id, label: "Identity ID", secret: false) }.buttonStyle(.vaultCompact).accessibilityLabel("Copy identity ID")522                    }523                }524                LabeledField(label: "Private key (SPV_AGENT_KEY)") {525                    HStack(alignment: .center) {526                        Group {527                            if revealed { Text(created.privateKey).font(.system(.caption, design: .monospaced)).foregroundStyle(Palette.text).textSelection(.enabled).fixedSize(horizontal: false, vertical: true) }528                            else { Text(String(repeating: "•", count: 28)).font(.secret).foregroundStyle(Palette.muted) }529                        }530                        .accessibilityLabel(revealed ? "Private key, revealed" : "Private key, hidden")531                        .accessibilityIdentifier("connect-identity-key")532                        Spacer(minLength: 6)533                        IconButton(systemName: revealed ? "eye.slash" : "eye", label: revealed ? "Hide private key" : "Reveal private key") { revealed.toggle() }534                        Button("Copy") { model.copy(created.privateKey, label: "Private key") }.buttonStyle(.vaultPrimary).accessibilityIdentifier("connect-identity-key-copy").accessibilityLabel("Copy private key")535                    }536                }537                Text("The workload signs its requests with this key (the reference client takes the server address, this identity ID and the key, usually from the environment variable SPV_AGENT_KEY). Anyone holding it can act as this identity within its grants: revoke the identity if the key leaks.")538                    .font(.caption).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)539            }540            .interactiveDismissDisabled()541        } else {542            SheetFrame(title: "New workload identity", confirmLabel: "Create identity", canConfirm: !name.trimmingCharacters(in: .whitespaces).isEmpty, busy: model.busy, confirmID: "connect-identity-create", onConfirm: create) {543                LabeledField(label: "Name") { TextField("", text: $name).textFieldStyle(.vault).accessibilityIdentifier("connect-identity-name").accessibilityLabel("Name") }544                LabeledField(label: "Kind") {545                    Picker("Kind", selection: $kind) {546                        Text("Agent (AI, autonomous)").tag("agent")547                        Text("Service (deterministic)").tag("service")548                    }549                    .pickerStyle(.segmented).labelsHidden().accessibilityIdentifier("connect-identity-kind")550                }551                Text(kind == "agent" ? "Agents always need a human approval, per lease or per use. They never get access to your personal vault."552                     : "Services run fixed code and may be granted unattended access to a specific secret.")553                    .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)554                Text("A signing key pair is generated here. An identity can do nothing until you create a grant for it.").font(.caption).foregroundStyle(Palette.muted)555                ErrorText(text: error)556            }557        }558    }559560    private func create() {561        let n = String(name.trimmingCharacters(in: .whitespaces).prefix(64)), k = kind562        Task {563            var result: WorkloadIdentitySecret?564            error = await model.perform { result = try await model.engine.createIdentity(name: n, kind: k) }565            if let result { created = result; await onDone() }566        }567    }568}569570private struct NewGrantSheet: View {571    @Environment(AppModel.self) private var model572    @Environment(\.dismiss) private var dismiss573    let data: ConnectOverview574    let onDone: () async -> Void575    @State private var identityId = ""576    @State private var secretId = ""577    @State private var mode = "operate"578    @State private var approval = "lease"579    @State private var leaseMin = "5"580    @State private var maxUses = ""581    @State private var expiry = 7 * 86400582    @State private var methods: Set<String> = []583    @State private var pathPrefix = ""584    @State private var error: String?585586    private static let expiries: [(label: String, seconds: Int)] = [("1 hour", 3600), ("1 day", 86400), ("7 days", 7 * 86400), ("30 days", 30 * 86400), ("90 days", 90 * 86400), ("1 year", 365 * 86400)]587    private var ids: [ConnectIdentity] { data.identities.filter { !$0.revoked } }588    private var isAgent: Bool { ids.first { $0.id == identityId }?.kind == "agent" }589    /// Agents can never be unattended; a raw read always needs an approval.590    private var effApproval: String { (isAgent || mode == "read") && approval == "never" ? "lease" : approval }591    private var pathOK: Bool { pathPrefix.isEmpty || (pathPrefix.hasPrefix("/") && pathPrefix.count <= 201 && !pathPrefix.contains(where: \.isWhitespace)) }592    private var secretIsHTTP: Bool { data.secrets.first { $0.id == secretId }?.kind.hasPrefix("http-") ?? false }593594    var body: some View {595        SheetFrame(title: "New grant", confirmLabel: "Create grant", canConfirm: !identityId.isEmpty && !secretId.isEmpty && pathOK, busy: model.busy, confirmID: "connect-grant-create", onConfirm: create) {596            LabeledField(label: "Identity") {597                Picker("Identity", selection: $identityId) { ForEach(ids) { Text("\($0.name) (\($0.kind))").tag($0.id) } }.labelsHidden().accessibilityIdentifier("connect-grant-identity")598            }599            LabeledField(label: "Managed secret") {600                Picker("Managed secret", selection: $secretId) { ForEach(data.secrets) { Text($0.name).tag($0.id) } }.labelsHidden().accessibilityIdentifier("connect-grant-secret")601            }602            LabeledField(label: "Mode") {603                Picker("Mode", selection: $mode) {604                    Text("Operate (brokered)").tag("operate")605                    Text("Read (raw value)").tag("read")606                }607                .pickerStyle(.segmented).labelsHidden().accessibilityIdentifier("connect-grant-mode")608            }609            if mode == "operate" {610                Text("SP Vault performs the HTTP call or signature itself and injects the credential. The workload never sees the secret.")611                    .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)612            } else {613                Callout(kind: .danger, title: "Read hands over the raw secret",614                        text: "The workload receives the secret itself and can then disclose it — in logs, in a prompt, to another service. Every read needs a human approval. Prefer “operate”.")615            }616            LabeledField(label: "Human approval") {617                Picker("Human approval", selection: Binding(get: { effApproval }, set: { approval = $0 })) {618                    if !isAgent && mode != "read" { Text("Never").tag("never") }619                    Text("Per lease").tag("lease")620                    Text("Each use").tag("each")621                }622                .pickerStyle(.segmented).labelsHidden().accessibilityIdentifier("connect-grant-approval")623            }624            Text((isAgent ? "Agents cannot have “never”: " : "") + (effApproval == "never" ? "The service uses the secret unattended, within the limits below."625                 : effApproval == "lease" ? "You approve once; the identity may then use the secret until the lease expires." : "You approve every single use.")626                 + (mode == "read" ? " Whatever is chosen here, the server asks for an approval at every delivery of a raw secret." : ""))627                .font(.callout).foregroundStyle(Palette.muted).fixedSize(horizontal: false, vertical: true)628            HStack(alignment: .top, spacing: 12) {629                LabeledField(label: "Lease duration (minutes)", hint: "0.5 – 60") {630                    TextField("", text: $leaseMin).textFieldStyle(.vault).rawTextInput().disabled(effApproval != "lease").accessibilityLabel("Lease duration in minutes")631                }632                LabeledField(label: "Maximum uses (optional)") {633                    TextField("", text: $maxUses).textFieldStyle(.vault).rawTextInput().accessibilityIdentifier("connect-grant-maxuses").accessibilityLabel("Maximum uses")634                }635            }636            LabeledField(label: "Grant expires after") {637                Picker("Grant expires after", selection: $expiry) { ForEach(Self.expiries, id: \.seconds) { Text($0.label).tag($0.seconds) } }.labelsHidden().accessibilityIdentifier("connect-grant-expiry")638            }639            if secretIsHTTP && mode == "operate" {640                LabeledField(label: "Path prefix (optional)", error: pathOK ? nil : "Must start with / and contain no spaces") {641                    TextField("/v1/", text: $pathPrefix).textFieldStyle(.vaultMono).rawTextInput().accessibilityLabel("Path prefix")642                }643                LabeledField(label: "Restrict methods (optional)", hint: "None selected = every method the secret allows.") { MethodChecks(label: "Restrict to method", selection: $methods) }644            }645            ErrorText(text: error)646        }647        .onAppear {648            if identityId.isEmpty { identityId = ids.first?.id ?? "" }649            if secretId.isEmpty { secretId = data.secrets.first?.id ?? "" }650        }651    }652653    private func create() {654        var constraints = JSONObject()655        if secretIsHTTP && mode == "operate" {656            if !methods.isEmpty { constraints["methods"] = .array(ConnectKinds.methods.filter(methods.contains).map { .string($0) }) }657            if !pathPrefix.isEmpty { constraints["pathPrefix"] = .string(pathPrefix) }658        }659        let minutes = Double(leaseMin.replacingOccurrences(of: ",", with: ".")) ?? 5660        let lease = max(30, min(3600, Int((minutes * 60).rounded())))661        let uses = Int(maxUses.trimmingCharacters(in: .whitespaces)) ?? 0662        let grant = NewConnectGrant(identityId: identityId, secretId: secretId, mode: mode, approval: effApproval, expiresInSec: expiry, leaseTtlSec: lease,663                                    maxUses: uses > 0 ? uses : nil, constraints: .object(constraints))664        Task {665            error = await model.perform("Grant created") { try await model.engine.createGrant(grant) }666            if error == nil { await onDone(); dismiss() }667        }668    }669}670
Files main
Menu

Theme