GebSecure 0.2.1
See the version list below for details.
dotnet add package GebSecure --version 0.2.1
NuGet\Install-Package GebSecure -Version 0.2.1
<PackageReference Include="GebSecure" Version="0.2.1" />
<PackageVersion Include="GebSecure" Version="0.2.1" />
<PackageReference Include="GebSecure" />
paket add GebSecure --version 0.2.1
#r "nuget: GebSecure, 0.2.1"
#:package GebSecure@0.2.1
#addin nuget:?package=GebSecure&version=0.2.1
#tool nuget:?package=GebSecure&version=0.2.1
GebSecure .NET SDK
Official .NET client for the GebSecure AI Agent Security & Governance Platform. It covers authorization decisions, secure execution with human approvals, delegation, and agent authentication.
- NuGet:
GebSecure, targetingnet8.0andnetstandard2.0(.NET Framework 4.6.2+, .NET Core 2.0+, Unity). - Async-first: every call takes a
CancellationToken. It usesHttpClientandSystem.Text.Json. - Behaves the same as the TypeScript, Python, Go and Java SDKs. Every SDK replays one shared conformance
suite (
sdks/conformance).
dotnet add package GebSecure
Quick start
using GebSecure;
using GebSecure.Auth;
using GebSecure.Models;
using var client = new GebSecureClient(new GebSecureClientOptions
{
GatewayUrl = "https://gateway.gebsecure.dev",
ApiUrl = "https://api.gebsecure.dev",
Auth = GebSecureAuth.ApiKey(Environment.GetEnvironmentVariable("GEBSECURE_API_KEY")!),
});
var guard = await client.GuardAsync("refunds:create", "stripe:charge/ch_123",
new Dictionary<string, object?> { ["amount"] = 250, ["currency"] = "USD" });
if (guard.Allowed) { /* act */ }
else Console.WriteLine($"{guard.Decision.Decision}: {guard.Decision.Reason}");
GebSecureClient.FromEnvironment() reads these environment variables:
GEBSECURE_GATEWAY_URLGEBSECURE_API_URLGEBSECURE_API_KEYorGEBSECURE_CLIENT_SECRET
Authentication
| Method | Code |
|---|---|
API key (gsk_…) |
GebSecureAuth.ApiKey(key) |
Client secret (gsa_…) |
GebSecureAuth.ClientSecret(secret, clientId: null, scope: "authorize execute") |
| private_key_jwt | GebSecureAuth.PrivateKeyJwt("cred_…", SigningKey.FromPem(pem)) |
| Delegation (RFC 8693) | GebSecureAuth.Delegation("gsd_…", actor: <delegate agent's provider>, scope), or client.WithDelegation("gsd_…") |
| Pre-obtained token | GebSecureAuth.StaticToken(token) |
| None (log a user in) | GebSecureAuth.Unauthenticated(): only LoginAsync / RefreshSessionAsync work; other calls throw GebSecureConfigurationException before sending |
client.GetAccessTokenAsync() returns the current (cached/refreshed) access token, e.g. for GebSecure APIs the
SDK does not wrap.
- Token caching: tokens are cached and refreshed before they expire, at
expires_in − min(60 s, expires_in/2). Concurrent callers share one in-flight token request (single-flight). - 401 retry: a 401 on a cached token invalidates it and replays the request once.
- private_key_jwt keys: accepts Ed25519 (EdDSA), P-256 (ES256) and RSA ≥ 2048 (RS256) keys, as PKCS#8 PEM or
private JWK (
SigningKey.FromJwk). Each token request signs a fresh assertion with a uniquejtiand a 60-second lifetime (configurable, at most 300 s). - Assertion audience:
auddefaults to{ApiUrl}/v1/auth/token. Passaudience:if your server's public URL differs.
Decisions and execution
AuthorizeResult d = await client.AuthorizeAsync(new AuthorizeRequest { Action = "db:delete", Resource = "pg:orders/42" });
// d.Decision is Decision.Allow | Decision.Deny | Decision.ApprovalRequired. DENY is a result, not an exception.
ExecuteResult r = await client.ExecuteWithApprovalAsync(new ExecuteRequest
{
Connection = "stripe-prod",
Action = "refunds.create",
Input = new Dictionary<string, object?> { ["charge"] = "ch_123", ["amount"] = 250 },
}, new WaitOptions { Timeout = TimeSpan.FromMinutes(30), PollInterval = TimeSpan.FromSeconds(5) });
| Method | Endpoint |
|---|---|
AuthorizeAsync, AuthorizeBatchAsync, GuardAsync |
POST {gateway}/v1/authorize[/batch] |
ExecuteAsync, ExecuteWithApprovalAsync |
POST {gateway}/v1/execute |
GetExecutionAsync, ListExecutionsAsync, CancelExecutionAsync |
{gateway}/v1/executions… |
GetApprovalAsync, WaitForApprovalAsync |
GET {gateway}/v1/approvals/{id} |
ListAgentsAsync, GetAgentAsync |
GET {api}/v1/agents[/{id}] |
ListPoliciesAsync |
GET {api}/v1/policies |
ListApprovalsAsync |
GET {api}/v1/approvals |
CreateDelegationAsync |
POST {api}/v1/delegations |
ExecuteAsync returns an ExecuteResult whenever the server sends one. That includes denied (HTTP 403)
and failed (HTTP 502/504). A problem+json error body throws instead.
ExecuteWithApprovalAsync runs these steps:
- Execute the action.
- If the result is
awaiting_approval, wait for the approval. - Once it is granted, the GebSecure worker resumes the stored execution (consuming the approval), so the
helper polls
GetExecutionAsyncuntil the execution reaches a terminal state and returns it. It never executes a second time.
If the approval is rejected, expires or is cancelled, it throws ApprovalNotGrantedException. If the approval
is still pending at the deadline it throws ApprovalTimeoutException; if the approved execution has not finished
by then, GatewayTimeoutException (code timeout). A resumed execution that failed is returned with status
failed.
Retries, timeouts, cancellation
| Option | Default |
|---|---|
MaxRetries |
3 |
BaseDelay |
500 ms |
MaxDelay |
8 s |
MaxRetryAfter |
60 s |
Timeout (per attempt) |
30 s |
- Backoff: exponential with equal jitter.
- 429: always retried, honoring
Retry-After. - 502/503/504, network errors and timeouts: retried only for idempotent calls. Those are GETs, the token
grants, dry-run authorizations,
ExecuteAsyncwith anIdempotencyKey, and cancel. - Idempotency keys: when retries are enabled,
ExecuteAsyncadds ansdk-<uuid>idempotency key if you did not set one, so it can be retried safely. - Cancellation: cancelling the token aborts both the in-flight request and any backoff sleep.
- Tracing: every call sends a W3C
traceparent. Passnew RequestOptions { Traceparent = ... }to continue an existing trace.
Errors
Every error derives from GebSecureException, which exposes Status, Code, Detail, RequestId,
TraceId and Details.
Server errors are ApiException subclasses:
AuthenticationExceptionPermissionDeniedExceptionPolicyDeniedExceptionApprovalRequiredExceptionValidationExceptionRateLimitException, which addsRetryAfterNotFoundExceptionConflictExceptionUpstreamExceptionGatewayTimeoutExceptionUnavailableExceptionInternalExceptionSimulationFailedException(422 fromRunSimulationAsyncwithFailOnMismatch; carriesRun)
Client-side errors use Status 0:
GebSecureConnectionExceptionGatewayTimeoutException, for a client timeoutApprovalTimeoutExceptionApprovalNotGrantedExceptionGebSecureConfigurationException, for an authenticated call on an unauthenticated client
Runtime guardrails: inspection, DLP, agent spans, simulation
// Untrusted content (web page, email, RAG chunk, tool output) before the model reads it.
var r = await client.InspectAsync(new InspectRequest { Content = page, Source = ContentSource.Web, Origin = url });
if (r.Action == "BLOCK") return; // r.Content is null when blocked
var safe = r.Content; // sanitized / masked form; r.Injection.Score/Level, r.Dlp
// Sensitive data in a payload. DryRun = true evaluates without recording (and is retried like a read).
var scan = await client.DlpScanAsync(new DlpScanRequest { Content = payload, Direction = DlpDirection.Outbound, DryRun = true });
// Report the agent's own spans (LLM calls, planning) into the shared trace.
var span = Spans.Build("llm.plan", started, DateTimeOffset.UtcNow, new SpanOptions { Traceparent = incomingTraceparent });
await client.ReportSpansAsync(new[] { span });
await client.AuthorizeAsync(req, new RequestOptions { Traceparent = Spans.TraceparentOf(span) }); // child of the span
// Simulation in CI: FailOnMismatch turns a failed run into SimulationFailedException (with the full run).
try { await client.RunSimulationAsync(new SimulationRunRequest { EnvironmentId = env, ScenarioSetId = set, FailOnMismatch = true }); }
catch (SimulationFailedException e) { foreach (var x in e.Run.Results) Console.WriteLine($"{x.Label}: {string.Join("; ", x.Failures ?? new List<string>())}"); }
Management (control plane)
User sessions for CLIs and tools: log in on an unauthenticated client, then use the access token.
using var anon = new GebSecureClient(new GebSecureClientOptions { ApiUrl = api, Auth = GebSecureAuth.Unauthenticated() });
var session = await anon.LoginAsync(new LoginRequest { Email = email, Password = password }); // refresh token in the body
using var admin = new GebSecureClient(new GebSecureClientOptions { ApiUrl = api, Auth = GebSecureAuth.StaticToken(session.AccessToken) });
var rotated = await anon.RefreshSessionAsync(session.RefreshToken!); // rotates: store the new refresh token
| Area | Methods |
|---|---|
| Session | LoginAsync, RefreshSessionAsync (never retried), LogoutAsync, MeAsync |
| Policies | ListPoliciesAsync, GetPolicyAsync, CreatePolicyAsync, UpdatePolicyAsync (PUT, appends a version, not retried), DeletePolicyAsync, ValidatePolicyAsync, GetPolicyVersionAsync, DiffPolicyVersionsAsync, ListPolicyDeploymentsAsync, DeployPolicyAsync (a 412 deploy report is returned with Deployed = false), RollbackPolicyAsync, AddPolicyTestAsync, ReplacePolicyTestsAsync (PUT), DeletePolicyTestAsync, RunPolicyTestsAsync, SimulatePoliciesAsync |
| Agents | ListAgentsAsync, GetAgentAsync, CreateAgentAsync, UpdateAgentAsync (PATCH), SetAgentStatusAsync, DeleteAgentAsync, ListAgentCredentialsAsync, CreateAgentCredentialAsync, RotateCredentialAsync, RevokeCredentialAsync |
| Secrets | CreateSecretAsync, ListSecretsAsync, GetSecretAsync, UpdateSecretAsync, RotateSecretAsync, RevokeSecretAsync, DeleteSecretAsync — values are write-only, never returned and never logged |
| Connectors | ListConnectorsAsync, GetConnectorAsync, ListConnectionsAsync, GetConnectionAsync, CreateConnectionAsync, UpdateConnectionAsync, DeleteConnectionAsync, CheckConnectionHealthAsync, StartConnectionOAuthAsync, CompleteConnectionOAuthAsync, InstallClientCredentialsAsync, InstallJwtBearerAsync |
| Audit | SearchAuditAsync (AfterSeq tails new events oldest-first), GetAuditEventAsync, ExportAuditAsync (raw ndjson/csv/json), VerifyAuditAsync |
| Approvals | ListApprovalsAsync, GetApprovalDetailsAsync, DecideApprovalAsync (with the reviewed SnapshotHash) |
| Alerts | ListAlertsAsync, GetAlertAsync, UpdateAlertAsync |
| Traces | SearchTracesAsync, GetTraceAsync, ReplaySessionAsync |
Retries follow HTTP semantics: GET, PUT and DELETE are retried on 502/503/504 and network errors; POST and
PATCH only on 429 — unless you pass new RequestOptions { IdempotencyKey = "…" }, which sends
Idempotency-Key and makes the call retryable (only do this when repeating the request is safe).
Models
GebSecure.Models is generated from docs/openapi/*.json + sdks/spec/overlay.json by
node sdks/scripts/generate-models.mjs (never edit Generated/Models.g.cs by hand).
- Enums are open: their values are string constants, for example
Decision.AlloworExecutionStatus.AwaitingApproval, so values added by newer servers still deserialize. - Unknown fields are kept: they land in
AdditionalProperties.
Examples
examples/ is a console project with one example per scenario:
dotnet run --project examples -- authorize # authorize-then-act with Guard
dotnet run --project examples -- approval # ExecuteWithApproval
dotnet run --project examples -- pkjwt # private_key_jwt authentication
dotnet run --project examples -- delegation # create + exchange a delegation
dotnet run --project examples -- inspect # inspect content, report an agent span, authorize inside it
Development
dotnet build -c Release # builds net8.0 + netstandard2.0, tests and examples
dotnet test # unit + conformance tests (sdks/conformance/fixtures)
GEBSECURE_LIVE_TEST=1 dotnet test # adds the live tests (needs GEBSECURE_* env vars; see below)
dotnet pack src/GebSecure -c Release -o artifacts
Live tests (conformance §9): GEBSECURE_GATEWAY_URL, GEBSECURE_API_URL, an agent credential in
GEBSECURE_CLIENT_SECRET, GEBSECURE_ENVIRONMENT_ID, and for the management half GEBSECURE_LIVE_EMAIL /
GEBSECURE_LIVE_PASSWORD.
You need the .NET 8 SDK. Without it, run the same commands in Docker:
docker run --rm -v "$PWD/..:/src" -w /src/dotnet mcr.microsoft.com/dotnet/sdk:8.0 dotnet test.
For versioning and releases, see sdks/VERSIONING.md. Releases are published by
.github/workflows/sdk-dotnet.yml on sdk-dotnet-v* tags.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 was computed. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
| .NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
| .NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
| .NET Framework | net461 was computed. net462 was computed. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
| MonoAndroid | monoandroid was computed. |
| MonoMac | monomac was computed. |
| MonoTouch | monotouch was computed. |
| Tizen | tizen40 was computed. tizen60 was computed. |
| Xamarin.iOS | xamarinios was computed. |
| Xamarin.Mac | xamarinmac was computed. |
| Xamarin.TVOS | xamarintvos was computed. |
| Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETStandard 2.0
- BouncyCastle.Cryptography (>= 2.4.0)
- Microsoft.Bcl.AsyncInterfaces (>= 8.0.0)
- System.Text.Json (>= 8.0.5)
-
net8.0
- BouncyCastle.Cryptography (>= 2.4.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.