Skip to content

Latest commit

 

History

History
480 lines (359 loc) · 16.5 KB

File metadata and controls

480 lines (359 loc) · 16.5 KB

KeyCrypt Shield X API Reference

This reference is grounded in the repository's source code and generated API spec files. It covers the implemented Python SDK, REST API, gRPC API, GraphQL adapter surface, CLI commands, and runtime configuration model.

Source anchors:

Scope Notes

Python SDK

The primary SDK entry point is KeyCrypt from src/sdk/python_sdk_complete.py. It exposes a stateful KeyCryptSDK facade and a module-level singleton.

Public Types

Type Purpose
KeyCryptSDK Main SDK facade for file encryption, decryption, batch encryption, stream encryption, policy selection, and provider selection.
KeyCrypt Module-level singleton instance of KeyCryptSDK.
SDKSettings Immutable runtime settings snapshot.
BatchEncryptionResult Outcome of concurrent file encryption.
StreamEncryptionResult Outcome of stream encryption.

KeyCryptSDK

Initialization and configuration

Method Description
`init(settings: SDKSettings None = None)`
settings Immutable property exposing current settings.
`configure(config_file: str Path = "keycrypt.yaml")`
set_defaults(algorithm: str = "aes-256-gcm", compression: str = "zstd") Set the default algorithm and compression mode.
with_policy(policy_name: str) Clone the SDK with a policy override.
with_provider(provider_name: str) Clone the SDK with a provider override.
adaptive() Clone the SDK with adaptive algorithm selection enabled.

Encryption and decryption

Method Description
`encrypt(file: str Path, algorithm: str = "auto", policy: str = "default")`
`decrypt(encrypted_file: str Path
`batch_encrypt(files: Sequence[str Path], parallelism: int = 10)`
stream_encrypt(input_stream: BinaryIO, output_stream: BinaryIO) Encrypt a binary stream into the SDK's self-describing frame format.

SDK behavior summary

  • Encryption prefers the container-backed client when prefer_container_backend is enabled, then falls back to a portable local backend.
  • Adaptive mode uses the repo's AutoMLAlgorithmSelector when available and falls back to rule-based selection.
  • Supported algorithm aliases include aes, aes-gcm, aes-256-gcm, chacha, chacha20, and chacha20-poly1305.
  • Supported compression modes include none, zstd, gzip, and zlib.
  • Stream encryption writes a KCS1 header followed by JSON metadata and framed encrypted chunks.

SDKSettings

Field Type Default Notes
algorithm str aes-256-gcm Default encryption algorithm.
compression str zstd Default compression mode.
policy str default Default policy label.
provider str auto Default provider hint.
key_store_dir Path Path.cwd() / ".keycrypt-sdk" Local key store directory.
output_dir `Path None` None
prefer_container_backend bool True Prefer container-backed execution first.
adaptive_enabled bool False Enable adaptive algorithm selection.

Result types

  • BatchEncryptionResult.successful: list of successful EncryptedFile artifacts.
  • BatchEncryptionResult.failed: list of (Path, Exception) failures.
  • BatchEncryptionResult.elapsed_seconds: total run time.
  • BatchEncryptionResult.parallelism: worker count used.
  • StreamEncryptionResult.bytes_read: plaintext bytes consumed.
  • StreamEncryptionResult.bytes_written: framed ciphertext bytes written.
  • StreamEncryptionResult.algorithm, policy, provider: effective runtime choices.

REST API

The HTTP API is described in docs/openapi.json. All protected endpoints use HTTP bearer auth.

Authentication

Endpoint Method Purpose
/auth/token POST Exchange credentials for a bearer token.

TokenRequest

Field Type Required
username string Yes
password string Yes

TokenResponse

Field Type Required Notes
access_token string Yes Bearer token value.
token_type string No Defaults to bearer.
expires_at number Yes Expiration timestamp.

Encryption

Endpoint Method Purpose
/encrypt POST Encrypt an uploaded file.
/decrypt POST Decrypt a ciphertext payload.

EncryptResponse

Field Type Required Notes
key_id string | null No Associated key identifier.
algorithm string Yes Effective encryption algorithm.
encrypted_file_b64 string Yes Base64 ciphertext.
metadata object Yes Arbitrary response metadata.

DecryptRequest

Field Type Required Notes
encrypted_file_b64 string Yes Base64 ciphertext.
nonce_b64 string Yes Base64 nonce.
key_b64 string | null No Explicit key material.
key_id string | null No Key lookup identifier.
aad string | null No Additional authenticated data.

DecryptResponse

Field Type Required Notes
plaintext_b64 string Yes Base64 plaintext.
metadata object Yes Arbitrary response metadata.

Key Lifecycle

Endpoint Method Purpose
/keys/generate POST Generate a new key.
/keys/{key_id} GET Retrieve key metadata.
/keys/{key_id}/rotate POST Rotate a key.

GenerateKeyRequest

Field Type Required Default
algorithm string No AES-256-GCM

GenerateKeyResponse

Field Type Required Notes
key_id string Yes Key identifier.
algorithm string Yes Effective algorithm.
created_at number Yes Creation timestamp.
expires_at number | null Yes Expiration timestamp, if any.
public_metadata object Yes Non-secret metadata.

RotateKeyRequest

Field Type Required
reason string Yes

RotateKeyResponse

Field Type Required
old_key_id string Yes
new_key_id string Yes
algorithm string Yes
revoked_reason string Yes

System

Endpoint Method Purpose
/status GET Return health, security state, and metrics.
/metrics GET Return metrics payload.

StatusResponse

Field Type Required
health string Yes
timestamp number Yes
security_state string Yes
metrics object Yes

REST security model

  • Protected endpoints require Authorization: Bearer <token>.
  • The OpenAPI document also defines standard validation error responses.
  • The /encrypt path accepts multipart file upload in the generated spec.

gRPC API

The gRPC service is defined in src/api/crypto_service.proto and implemented in src/api/grpc_api.py.

Service: keycrypt.v1.CryptoService

RPC Type Request Response
Encrypt unary EncryptRequest EncryptResponse
Decrypt unary DecryptRequest DecryptResponse
GenerateKey unary KeyGenRequest KeyGenResponse
StreamEncrypt client streaming stream FileChunk EncryptedChunk

Messages

EncryptRequest

Field Type
plaintext bytes
algorithm string
key_id string
key bytes
aad string

EncryptResponse

Field Type
ciphertext bytes
key_id string
algorithm string
nonce bytes
metadata_json string

DecryptRequest

Field Type
ciphertext bytes
key_id string
key bytes
nonce bytes
aad string

DecryptResponse

Field Type
plaintext bytes
metadata_json string

KeyGenRequest

Field Type
algorithm string

KeyGenResponse

Field Type
key_id string
algorithm string
created_at int64
expires_at int64
metadata_json string
key_material bytes

FileChunk

Field Type
chunk_id int64
data bytes
eof bool
filename string
algorithm string
key_id string
key bytes
aad string

EncryptedChunk

Field Type
encrypted_data bytes
key_id string
algorithm string
metadata_json string

Server behavior

  • Encrypt resolves a key from either inline key material, key_id, or generated defaults.
  • Decrypt accepts either inline key material or key_id lookup.
  • GenerateKey returns key metadata and raw key material.
  • StreamEncrypt accepts a stream of numbered chunks, sorts them by chunk_id, encrypts each chunk separately, and returns a concatenated payload plus JSON metadata.
  • The server installs authentication, logging, and error-handling interceptors.

gRPC auth

  • The server expects bearer token metadata in authorization.
  • Missing or invalid tokens produce UNAUTHENTICATED responses.

GraphQL Adapter

The repository contains a GraphQL client adapter at src/adapters/graphql_adapter/graphql_client.py, but not a server-side schema file.

GraphQLClient

Method Description
query(graphql_query, variables) Execute a GraphQL query synchronously.
mutation(graphql_mutation, variables) Execute a GraphQL mutation synchronously.
batch_query(queries) Execute multiple queries as a batch when the transport supports it.
query_async(graphql_query, variables=None) Async query execution.
mutation_async(graphql_mutation, variables=None) Async mutation execution.
batch_query_async(queries) Async batch execution.
subscribe(subscription, variables=None) Async subscription stream.
close() / aclose() Close pooled sessions and clear cache.

Client capabilities

  • Supports HTTP and WebSocket transports when gql transports are installed.
  • Maintains pooled query and subscription sessions.
  • Applies TTL-based query caching.
  • Supports Authorization headers via access_token.
  • Falls back to per-request execution when batch transport support is unavailable.

GraphQL scope limitation

No schema, query, mutation, or subscription definitions were found under src/api/ for a server implementation. For that reason, this reference documents the adapter contract only.

CLI Reference

The CLI entry point is src/cli/main.py. It registers the core commands plus the advanced and interactive extensions.

Global options

Option Description
--verbose Enable verbose logging.
--json Emit machine-readable JSON output.

Core commands

Command Description
encrypt Encrypt a file and write ciphertext plus a metadata sidecar.
decrypt Decrypt a file using metadata or --key-id.
keygen Generate a new key entry and print non-secret metadata.
status Show security state, active keys, and runtime metrics.
config Launch the interactive configuration wizard.
interactive Launch the REPL.

Advanced commands

These are registered from src/cli/advanced_cli.py.

Command Description
wizard Interactive setup wizard.
doctor Environment and configuration diagnostics.
benchmark Local encryption benchmark.
explain Explain an operation before running it.
replay Replay audit log entries.
diff Compare encrypted artifacts using metadata only.
version --check Compare the installed version against PyPI.
completion Print shell completion instructions.
manpage Generate a man page for the CLI.

Interactive REPL commands

The REPL is implemented in src/cli/interactive_mode.py.

Command Description
encrypt <file> Encrypt a file from the shell.
decrypt <file> Decrypt a file from the shell.
rotate-key <key-id> Rotate a key with an optional reason.
status Show key and audit counts.
save-session [file] Persist interactive state.
load-session [file] Restore interactive state.
help / ? Show command help.
exit / quit Leave the REPL.

CLI output model

  • Commands use Rich panels and tables in human mode.
  • --json emits compact JSON for automation.
  • Errors are surfaced as Click exceptions with friendly messages.

Configuration Reference

The runtime configuration model is defined in src/core/config.py.

SecurityLevel

Value Meaning
LOW Reduced security posture.
NORMAL Default posture.
ELEVATED Increased security posture.
CRITICAL Highest non-lockdown posture.

Config

Field Type Default Notes
security_level SecurityLevel NORMAL Security posture.
enable_quantum bool True Enable quantum-capable paths.
enable_consciousness bool False Experimental toggle.
encryption_algorithm str AES-256-GCM Must be one of the allowed algorithm names.
key_rotation_days int 30 Constrained to 1..3650.
storage_backend str filesystem Must be one of filesystem, sqlite, postgres, or s3.

Configuration loading

  • Config.from_yaml(path) loads YAML and merges environment variable overrides.
  • load_config(config_path=None) returns file-based config when a path is supplied, otherwise environment/default-based config.
  • Environment variables use the KEYCRYPT_ prefix.
  • The .env file is loaded automatically by the settings model.

Practical Examples

Python SDK

from pathlib import Path
from src.sdk.python_sdk_complete import KeyCrypt

artifact = KeyCrypt.with_policy("default").encrypt(Path("report.txt"))
restored = KeyCrypt.decrypt(artifact)

REST

curl -H "Authorization: Bearer $TOKEN" \
  http://127.0.0.1:8000/status

gRPC

import grpc

# Use src.adapters.grpc_adapter.grpc_client.GRPCClient for the high-level client.

CLI

keycrypt encrypt report.txt --algorithm AES
keycrypt status --json
keycrypt interactive

Generated From

This document was assembled from the following repository sources: