Code Governance
AxonFlow's Code Governance feature enables organizations to observe and audit LLM-generated code. Every code artifact in AI responses is automatically detected, analyzed, and logged for compliance purposes.
See complete working examples in the AxonFlow examples repository.
Overview
When an LLM generates code in response to a user query, AxonFlow automatically:
- Detects code blocks in the response
- Identifies the programming language
- Categorizes the code type (function, class, script, etc.)
- Counts potential security issues (secrets, unsafe patterns)
- Logs metadata for audit and compliance
This happens transparently with zero configuration required.
Code Detection
Supported Languages
AxonFlow detects code in 14 programming languages:
| Language | Detection Patterns |
|---|---|
| Python | def, class, import, decorators |
| Go | package, func, type struct |
| TypeScript | interface, type annotations, enum |
| JavaScript | const, let, function, arrow functions |
| Java | public class, import java. |
| SQL | SELECT, INSERT, UPDATE, DELETE |
| Ruby | def, class <, module, require |
| Rust | fn, let mut, impl, struct |
| C/C++ | #include, int main, void |
| Bash | Shebang, if [, for in, while |
| YAML | Key-value pairs, lists |
| JSON | Object structure |
| Dockerfile | FROM, RUN, COPY, ENTRYPOINT |
| Terraform | resource, provider, variable |
Code Types
Detected code is categorized as:
- function - Function or method definitions
- class - Class, struct, or interface definitions
- script - Executable scripts with entry points
- config - Configuration files (YAML, JSON, Terraform, Dockerfile)
- snippet - Small code fragments (< 10 lines)
- module - Larger code modules
Audit Logging
Every API response that contains code includes a code_artifact field in the policy_info:
{
"success": true,
"data": { ... },
"policy_info": {
"code_artifact": {
"is_code_output": true,
"language": "python",
"code_type": "function",
"size_bytes": 245,
"line_count": 12,
"policies_checked": ["code-secrets", "code-unsafe", "code-compliance"],
"secrets_detected": 0,
"unsafe_patterns": 0
}
}
}
Audit Fields
| Field | Description |
|---|---|
is_code_output | Whether the response contains code |
language | Detected programming language |
code_type | Category of code (function, class, etc.) |
size_bytes | Total size of detected code |
line_count | Number of lines of code |
policies_checked | Code governance policies evaluated |
secrets_detected | Count of potential secrets found |
unsafe_patterns | Count of unsafe code patterns |
Security Detection
Secret Patterns
AxonFlow counts (but does not block by default) potential secrets in generated code:
- AWS access keys and secret keys
- API keys and tokens
- GitHub personal access tokens
- JWT tokens
- Private keys (RSA, SSH, EC)
- Bearer tokens
- Password assignments
Secret detection in Code Governance is for audit purposes only. To block responses containing secrets, configure a static policy with the code-secrets category.
Unsafe Code Patterns
The following patterns are flagged as potentially unsafe:
| Pattern | Risk |
|---|---|
eval(), exec() | Code injection |
os.system(), subprocess.call() | Shell injection |
pickle.load() | Insecure deserialization |
yaml.load() | YAML deserialization attack |
dangerouslySetInnerHTML | React XSS vulnerability |
innerHTML = | DOM-based XSS |
child_process.exec() | Node.js command injection |
Runtime.getRuntime().exec() | Java command injection |
privileged: true | Kubernetes privilege escalation |
Policy Categories
Code Governance introduces three policy categories:
| Category | Description |
|---|---|
code-secrets | Detect and optionally block secrets in code |
code-unsafe | Detect and optionally block unsafe patterns |
code-compliance | Enforce code compliance requirements |
You can create static policies using these categories to enforce code security standards.
Example Usage
Python SDK
from axonflow import AxonFlow
async def main():
async with AxonFlow(endpoint="http://localhost:8080") as client:
response = await client.execute_query(
user_token="developer-123",
query="Write a Python function to hash passwords",
request_type="chat"
)
# Check for code in response
if response.policy_info and response.policy_info.code_artifact:
artifact = response.policy_info.code_artifact
print(f"Language: {artifact.language}")
print(f"Type: {artifact.code_type}")
print(f"Size: {artifact.size_bytes} bytes")
print(f"Lines: {artifact.line_count}")
print(f"Secrets detected: {artifact.secrets_detected}")
print(f"Unsafe patterns: {artifact.unsafe_patterns}")
import asyncio
asyncio.run(main())
TypeScript SDK
import { AxonFlow } from '@axonflow/sdk';
const client = new AxonFlow({ endpoint: 'http://localhost:8080' });
const response = await client.executeQuery({
userToken: 'developer-123',
query: 'Write a TypeScript interface for user data',
requestType: 'chat'
});
if (response.policyInfo?.codeArtifact) {
const { language, code_type, size_bytes, line_count, secrets_detected, unsafe_patterns } = response.policyInfo.codeArtifact;
console.log(`Generated ${code_type} in ${language}`);
console.log(`Size: ${size_bytes} bytes, Lines: ${line_count}`);
if (unsafe_patterns > 0) {
console.warn(`Warning: ${unsafe_patterns} unsafe pattern(s) detected`);
}
}
Go SDK
import axonflow "github.com/getaxonflow/axonflow-sdk-go/v3"
client := axonflow.NewClient(axonflow.AxonFlowConfig{
Endpoint: "http://localhost:8080",
})
response, err := client.ExecuteQuery(
"developer-123",
"Write a Go function to validate email addresses",
"chat",
map[string]interface{}{},
)
if response.PolicyInfo != nil && response.PolicyInfo.CodeArtifact != nil {
artifact := response.PolicyInfo.CodeArtifact
fmt.Printf("Language: %s\n", artifact.Language)
fmt.Printf("Type: %s\n", artifact.CodeType)
fmt.Printf("Size: %d bytes\n", artifact.SizeBytes)
fmt.Printf("Unsafe Patterns: %d\n", artifact.UnsafePatterns)
}
Java SDK
import com.getaxonflow.sdk.AxonFlow;
import com.getaxonflow.sdk.AxonFlowConfig;
import com.getaxonflow.sdk.types.ClientRequest;
import com.getaxonflow.sdk.types.ClientResponse;
import com.getaxonflow.sdk.types.CodeArtifact;
AxonFlow client = AxonFlow.create(AxonFlowConfig.builder()
.endpoint("http://localhost:8080")
.build());
ClientResponse response = client.executeQuery(
ClientRequest.builder()
.query("Write a Java function to validate email")
.userToken("developer-123")
.build()
);
if (response.getPolicyInfo() != null) {
CodeArtifact artifact = response.getPolicyInfo().getCodeArtifact();
if (artifact != null) {
System.out.printf("Language: %s%n", artifact.getLanguage());
System.out.printf("Type: %s%n", artifact.getCodeType());
System.out.printf("Size: %d bytes%n", artifact.getSizeBytes());
System.out.printf("Unsafe Patterns: %d%n", artifact.getUnsafePatterns());
}
}
Community vs Enterprise
| Capability | Community | Enterprise |
|---|---|---|
| Code artifact detection | ✅ | ✅ |
| Language detection | ✅ | ✅ |
| Audit logging | ✅ | ✅ |
| Secret/unsafe pattern counting | ✅ | ✅ |
| Git provider integration | ❌ | ✅ |
| PR creation from LLM code | ❌ | ✅ |
| Code governance dashboard | ❌ | ✅ |
For Git integration and PR creation capabilities, see Enterprise Code Governance.
CI/CD Integration
Code Governance integrates with CI/CD pipelines and pull request workflows. When LLM-generated code is committed, AxonFlow can evaluate it as part of your existing review process.
PR Workflow (Enterprise)
In Enterprise Edition, AxonFlow can be configured as a GitHub or GitLab webhook to automatically scan LLM-generated code in pull requests:
# .github/workflows/axonflow-code-scan.yml
name: AxonFlow Code Governance
on: [pull_request]
jobs:
code-governance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- name: Scan LLM-generated code
run: |
curl -X POST http://your-axonflow:8080/api/v1/code-governance/scan \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${{ secrets.AXONFLOW_API_KEY }}" \
-d '{
"repository": "${{ github.repository }}",
"pr_number": ${{ github.event.pull_request.number }},
"commit_sha": "${{ github.sha }}"
}'
Pre-Commit Hook
Use a local pre-commit hook to scan code before it leaves the developer workstation:
#!/bin/bash
# .git/hooks/pre-commit
STAGED=$(git diff --cached --name-only --diff-filter=ACM)
for FILE in $STAGED; do
RESULT=$(curl -s -X POST http://localhost:8080/api/v1/code-governance/check \
-H "Content-Type: application/json" \
-d "{\"file\": \"$FILE\", \"content\": $(jq -Rs . < "$FILE")}")
SECRETS=$(echo "$RESULT" | jq '.secrets_detected')
if [ "$SECRETS" -gt 0 ]; then
echo "Secrets detected in $FILE - commit blocked"
exit 1
fi
done
Best Practices
- Monitor
secrets_detected- Investigate any response with secrets > 0 - Track
unsafe_patterns- Review code with unsafe patterns before use - Use policy categories - Create policies for
code-secretsandcode-unsafe - Log for compliance - Store
code_artifactmetadata for audit trails - Review by language - Some languages require more scrutiny (shell scripts, SQL)