docs: update README with private key features and export documentation

main
stef 2025-12-07 10:09:56 +01:00
parent c7427dae28
commit 3cb1bb4c47
1 changed files with 113 additions and 309 deletions

422
README.md
View File

@ -9,6 +9,8 @@ API Go complète pour gérer une Infrastructure à Clé Publique (PKI) avec hié
- ✅ **Signature de certificats** : Certificats auto-signés ou signés par une CA
- ✅ **Gestion des révocations** : Révocation et CRL (Certificate Revocation List)
- ✅ **Stockage pluggable** : MemoryStore (développement) ou MongoDB (production)
- ✅ **Export de certificats** : PEM, DER, avec clé privée, chaîne complète
- ✅ **Clés privées** : Stockage et récupération sécurisés pour tous les certificats (JSON + export fichier)
- ✅ **Cryptographie** : X.509, RSA 2048-bit, signatures HS256 pour JWT
## Architecture
@ -36,7 +38,9 @@ pkiapi/
│ ├── mongo.go # MongoStore (persistance)
│ ├── util.go # Helpers sérialisation
│ └── errors.go # Erreurs storage
└── go.mod
├── tests/ # Scripts de test
├── go.mod
└── docker-compose.yaml # Orchestration services
```
## Démarrage rapide
@ -58,13 +62,11 @@ export PORT=8080
# Serveur lancé sur http://localhost:8080
```
**Mode production (MongoDB):**
**Mode production (MongoDB via Docker Compose):**
```bash
export STORAGE_TYPE=mongodb
export MONGO_URI=mongodb://mongodb-server:27017
export MONGO_DB=pkiapi-prod
export JWT_SECRET_KEY=super-secret-key
./pkiapi
docker compose up -d --build
# L'API est disponible sur http://localhost:8080
# MongoDB est disponible sur mongodb://localhost:27017
```
### 3. Obtenir un token JWT
@ -110,34 +112,6 @@ curl -X POST http://localhost:8080/api/v1/login \
### 🔑 Autorités de Certification (Authentifiés)
#### GET /api/v1/ca
Liste toutes les autorités de certification.
**Requête :**
```bash
TOKEN="<your_token>"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/ca
```
**Réponse :**
```json
{
"cas": [
{
"id": "16de28da-f25e-49cd-81de-a929d34dfe08",
"subject": "CN=Root CA,O=Example,C=FR",
"issuer": "CN=Root CA,O=Example,C=FR",
"not_before": "2025-12-06T22:52:48Z",
"not_after": "2035-12-04T22:52:48Z",
"serial_number": "574847517"
}
]
}
```
---
#### POST /api/v1/ca
Crée une nouvelle autorité de certification auto-signée.
@ -163,6 +137,7 @@ curl -X POST http://localhost:8080/api/v1/ca \
"not_after": "2035-12-04T21:45:01Z",
"serial_number": "546965196",
"certificate": "MIIC5zCCAc+gAwIBAgIDCkUz...",
"private_key": "MIIEwAIBADANBgkqhkiG9w0BAQE...",
"is_ca": true
},
"created_by": "admin"
@ -172,7 +147,7 @@ curl -X POST http://localhost:8080/api/v1/ca \
---
#### GET /api/v1/ca/:id
Récupère une autorité de certification par ID.
Récupère une autorité de certification par ID (avec clé privée).
**Requête :**
```bash
@ -192,6 +167,7 @@ curl -H "Authorization: Bearer $TOKEN" \
"not_after": "2035-12-04T21:45:01Z",
"serial_number": "546965196",
"certificate": "MIIC5zCCAc+gAwIBAgIDCkUz...",
"private_key": "MIIEwAIBADANBgkqhkiG9w0BAQE...",
"is_ca": true
}
}
@ -216,58 +192,12 @@ curl -X POST http://localhost:8080/api/v1/ca/sign \
}"
```
**Réponse :**
```json
{
"ca": {
"id": "b2350d39-53c2-469a-802c-acc39707e352",
"subject": "CN=Intermediate CA,O=Example Inc,C=FR",
"not_before": "2025-12-06T21:45:09Z",
"not_after": "2030-12-05T21:45:09Z",
"serial_number": "576310632",
"certificate": "MIIDOTCCAiGgAwIBAgIEIlnNaD...",
"is_ca": true
},
"created_by": "admin",
"signed_by": "ff3ac5c5-08d1-401b-9e83-f18eda4c538b"
}
```
---
### 📜 Certificats (Authentifiés)
#### GET /api/v1/certificates
Liste tous les certificats.
**Requête :**
```bash
TOKEN="<your_token>"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/certificates
```
**Réponse :**
```json
{
"certificates": [
{
"id": "e12e08a9-adeb-404c-a7b7-a613b77dfe66",
"subject": "CN=server.example.com,O=Example Inc,C=FR",
"issuer": "CN=Intermediate CA,O=Example Inc,C=FR",
"not_before": "2025-12-06T21:45:09Z",
"not_after": "2026-12-06T21:45:09Z",
"serial_number": "46798982",
"revoked": false
}
]
}
```
---
#### POST /api/v1/certificates
Crée un certificat auto-signé.
Crée un certificat auto-signé avec clé privée.
**Requête :**
```bash
@ -292,6 +222,7 @@ curl -X POST http://localhost:8080/api/v1/certificates \
"not_after": "2026-12-06T21:41:38Z",
"serial_number": "673075",
"certificate": "MIIC5zCCAc+gAwIBAgIDCkUzMA0GCSq...",
"private_key": "MIIEwAIBADANBgkqhkiG9w0BAQE...",
"revoked": false
},
"created_by": "admin"
@ -300,45 +231,8 @@ curl -X POST http://localhost:8080/api/v1/certificates \
---
#### POST /api/v1/certificates/sign
Signe un certificat avec une CA.
**Requête :**
```bash
TOKEN="<your_token>"
CA_ID="b2350d39-53c2-469a-802c-acc39707e352"
curl -X POST http://localhost:8080/api/v1/certificates/sign \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"ca_id\": \"$CA_ID\",
\"subject\": \"CN=server.example.com,O=Example Inc,C=FR\",
\"validity_days\": 365
}"
```
**Réponse :**
```json
{
"certificate": {
"id": "e12e08a9-adeb-404c-a7b7-a613b77dfe66",
"subject": "CN=server.example.com,O=Example Inc,C=FR",
"issuer": "CN=Intermediate CA,O=Example Inc,C=FR",
"not_before": "2025-12-06T21:45:09Z",
"not_after": "2026-12-06T21:45:09Z",
"serial_number": "46798982",
"certificate": "MIIDFDCCAfygAwIBAgIEAsoYhjANBg...",
"revoked": false
},
"created_by": "admin",
"signed_by": "b2350d39-53c2-469a-802c-acc39707e352"
}
```
---
#### GET /api/v1/certificates/:id
Récupère un certificat par ID.
Récupère un certificat par ID (avec clé privée encodée en base64).
**Requête :**
```bash
@ -359,6 +253,7 @@ curl -H "Authorization: Bearer $TOKEN" \
"not_after": "2026-12-06T21:45:09Z",
"serial_number": "46798982",
"certificate": "MIIDFDCCAfygAwIBAgIEAsoYhjANBg...",
"private_key": "MIIEwAIBADANBgkqhkiG9w0BAQE...",
"revoked": false
}
}
@ -366,6 +261,25 @@ curl -H "Authorization: Bearer $TOKEN" \
---
#### POST /api/v1/certificates/sign
Signe un certificat avec une CA (avec clé privée).
**Requête :**
```bash
TOKEN="<your_token>"
CA_ID="b2350d39-53c2-469a-802c-acc39707e352"
curl -X POST http://localhost:8080/api/v1/certificates/sign \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{
\"ca_id\": \"$CA_ID\",
\"subject\": \"CN=server.example.com,O=Example Inc,C=FR\",
\"validity_days\": 365
}"
```
---
#### POST /api/v1/revoke
Révoque un certificat.
@ -382,15 +296,6 @@ curl -X POST http://localhost:8080/api/v1/revoke \
}"
```
**Réponse :**
```json
{
"message": "certificat révoqué",
"id": "e12e08a9-adeb-404c-a7b7-a613b77dfe66",
"reason": "Compromised key"
}
```
---
#### GET /api/v1/crl
@ -403,243 +308,142 @@ curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/crl
```
**Réponse :**
```json
{
"crl": [
{
"serial_number": "46798982",
"subject": "CN=server.example.com,O=Example Inc,C=FR"
}
],
"version": 1
}
```
---
### 📥 Export de Certificats (Authentifiés)
#### GET /api/v1/certificates/:id/export/pem
Exporte un certificat au format PEM (binaire/texte).
Exporte un certificat au format PEM.
**Requête :**
```bash
TOKEN="<your_token>"
CERT_ID="e12e08a9-adeb-404c-a7b7-a613b77dfe66"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/certificates/$CERT_ID/export/pem \
http://localhost:8080/api/v1/certificates/:id/export/pem \
-o certificate.pem
```
**Réponse :**
```
-----BEGIN CERTIFICATE-----
MIIDFDCCAfygAwIBAgIEAsoYhjANBg...
...base64...
-----END CERTIFICATE-----
```
---
#### GET /api/v1/certificates/:id/export/der
Exporte un certificat au format DER (binaire).
**Requête :**
```bash
TOKEN="<your_token>"
CERT_ID="e12e08a9-adeb-404c-a7b7-a613b77dfe66"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/certificates/$CERT_ID/export/der \
http://localhost:8080/api/v1/certificates/:id/export/der \
-o certificate.der
```
**Réponse :**
Format binaire DER directement (données binaires).
---
#### GET /api/v1/certificates/:id/export/pem-with-key
Exporte un certificat avec sa clé privée au format PEM (combiné).
Exporte certificat + clé privée au format PEM.
**Requête :**
```bash
TOKEN="<your_token>"
CERT_ID="e12e08a9-adeb-404c-a7b7-a613b77dfe66"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/certificates/$CERT_ID/export/pem-with-key \
http://localhost:8080/api/v1/certificates/:id/export/pem-with-key \
-o certificate_with_key.pem
```
**Réponse :**
```
-----BEGIN CERTIFICATE-----
MIIDFDCCAfygAwIBAgIEAsoYhjANBg...
...base64...
-----END CERTIFICATE-----
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQE...
...base64...
-----END PRIVATE KEY-----
#### GET /api/v1/certificates/:id/export/chain
Exporte la chaîne complète (certificat + CA parent).
```bash
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/certificates/:id/export/chain \
-o certificate_chain.pem
```
---
#### GET /api/v1/certificates/:id/export/chain
Exporte la chaîne de certificats (certificat + CA parent).
## Clés Privées
### Stockage et Récupération
Les clés privées sont **automatiquement stockées** pour:
- ✅ Tous les certificats auto-signés
- ✅ Tous les certificats signés par une CA
- ✅ Toutes les CAs (Root et Intermediate)
### Accès via JSON
Les clés privées sont incluses dans les réponses JSON:
- **Format**: Base64 PKCS#8 encodé
- **Champs**: `private_key` (optionnel, présent si disponible)
- **Endpoints retournant des clés privées**:
- `POST /api/v1/ca` - Création CA
- `GET /api/v1/ca/:id` - Récupération CA
- `POST /api/v1/ca/sign` - Création Sub-CA
- `POST /api/v1/certificates` - Création certificat
- `GET /api/v1/certificates/:id` - Récupération certificat
- `POST /api/v1/certificates/sign` - Signature certificat
### Accès via Export Fichier
Les clés privées peuvent aussi être exportées en fichier:
- **`/export/pem-with-key`** - Certificat + clé privée en PEM
- **`/export/chain`** - Chaîne complète (pour CAs parent)
### Base de Données
Les clés privées sont:
- ✅ Sauvegardées en MongoDB (champ `private_key` en base64)
- ✅ Chiffrées au repos (via votre configuration MongoDB)
- ✅ Accessibles uniquement avec authentification JWT
---
## Tests
### Scripts de Test Disponibles
**Requête :**
```bash
TOKEN="<your_token>"
CERT_ID="e12e08a9-adeb-404c-a7b7-a613b77dfe66"
curl -H "Authorization: Bearer $TOKEN" \
http://localhost:8080/api/v1/certificates/$CERT_ID/export/chain \
-o certificate_chain.pem
# Test complet (création CA, certificats, exports, revocation)
./tests/test_complete.sh
# Test spécifique des exports
./tests/test_exports.sh
# Test du stockage des clés privées
./tests/test_private_keys.sh
```
**Réponse :**
```
-----BEGIN CERTIFICATE-----
MIIDFDCCAfygAwIBAgIEAsoYhjANBg...
...certificat feuille...
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
MIIDOTCCAiGgAwIBAgIEIlnNaD...
...certificat CA parent...
-----END CERTIFICATE-----
```
### Résultats des Tests
Voir `tests/test_results.txt` pour les résultats détaillés des tests.
---
## Variables d'Environnement
- `JWT_SECRET_KEY` : Secret pour signer les tokens JWT (défaut: `your-secret-key-change-in-prod`)
```bash
export JWT_SECRET_KEY="your-secure-secret-key"
./pkiapi
# Stockage
export STORAGE_TYPE=memory # memory ou mongodb (défaut: memory)
export MONGO_URI=mongodb://localhost:27017
export MONGO_DB=pkiapi
# Serveur
export PORT=8080
export JWT_SECRET_KEY=your-secret-key
export GIN_MODE=release
```
---
## Exemple de flux complet
```bash
# 1. Obtenir un token
**Smoke Test Results**
- **Fichier de résultat :** `tests/smoke_result.txt` — sortie brute d'un smoke test automatisé (login → création Root CA → création Sub-CA → signature de certificat → révocation → récupération de la CRL).
- **Résumé :** le test vérifie que le flux complet fonctionne avec `STORAGE_TYPE=mongodb` (création des CA, signature, révocation) et que la CRL liste bien les certificats révoqués.
- **Reproduire localement :** démarrer la stack, puis exécuter les commandes de l'exemple de flux cidessus. Vous pouvez aussi lancer le script temporaire utilisé lors des tests :
```
# reconstruire et démarrer la stack
STORAGE_TYPE=mongodb docker compose up -d --build
# exécuter manuellement l'exemple de flux (ou utiliser jq pour extraire le token)
# voir la section "Exemple de flux complet" cidessus
```
Les résultats complets sont committés dans `tests/smoke_result.txt` pour référence.
TOKEN=$(curl -s -X POST http://localhost:8080/api/v1/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"admin"}' | jq -r '.token')
echo "Token: $TOKEN"
# 2. Créer une Root CA
ROOT_CA=$(curl -s -X POST http://localhost:8080/api/v1/ca \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d '{"subject":"CN=Root CA,O=Example,C=FR","validity_days":3650}')
ROOT_CA_ID=$(echo $ROOT_CA | jq -r '.ca.id')
echo "Root CA ID: $ROOT_CA_ID"
# 3. Créer une Sub-CA
SUB_CA=$(curl -s -X POST http://localhost:8080/api/v1/ca/sign \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"parent_ca_id\":\"$ROOT_CA_ID\",\"subject\":\"CN=Intermediate CA,O=Example,C=FR\",\"validity_days\":1825}")
SUB_CA_ID=$(echo $SUB_CA | jq -r '.ca.id')
echo "Sub-CA ID: $SUB_CA_ID"
# 4. Signer un certificat avec la Sub-CA
CERT=$(curl -s -X POST http://localhost:8080/api/v1/certificates/sign \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"ca_id\":\"$SUB_CA_ID\",\"subject\":\"CN=app.example.com,O=Example,C=FR\",\"validity_days\":365}")
CERT_ID=$(echo $CERT | jq -r '.certificate.id')
echo "Certificate ID: $CERT_ID"
# 5. Lister toutes les CAs
curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/ca | jq .
# 6. Lister tous les certificats
curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/certificates | jq .
# 7. Révoquer le certificat
curl -s -X POST http://localhost:8080/api/v1/revoke \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
-d "{\"certificate_id\":\"$CERT_ID\",\"reason\":\"Test\"}" | jq .
# 8. Voir la CRL
curl -s -H "Authorization: Bearer $TOKEN" http://localhost:8080/api/v1/crl | jq .
```
---
## Structure du projet
```
pkiapi/
├── cmd/main.go # Point d'entrée
├── internal/
│ ├── api/
│ │ ├── router.go # Routes Gin
│ │ ├── auth.go # Login
│ │ ├── ca.go # Handlers CA
│ │ └── certificates.go # Handlers certificats
│ ├── auth/
│ │ ├── jwt.go # JWT manager
│ │ └── middleware.go # Middleware JWT
│ ├── pki/
│ │ ├── certificate.go # Logique X.509
│ │ └── errors.go # Erreurs PKI
│ └── storage/
│ ├── store.go # Store thread-safe
│ └── errors.go # Erreurs storage
├── go.mod
├── go.sum
├── Makefile
├── README.md
└── .gitignore
```
---
## Conventions de code
## Conventions de Code
- **Gestion des erreurs** : Propagation simple sans wrapper
- **Concurrence** : `sync.RWMutex` pour le store
- **Cryptographie** : Stdlib Go (crypto/x509, crypto/rsa, crypto/rand)
- **JWT** : github.com/golang-jwt/jwt/v5
- **MongoDB** : go.mongodb.org/mongo-driver
---
## Future améliorations
## Améliorations Futures
- [x] Export des certificats (PEM, DER)
- [ ] Persistance en base de données (PostgreSQL)
- [x] Clés privées dans JSON responses
- [ ] Support OCSP (Online Certificate Status Protocol)
- [ ] Interface web pour gérer les CAs
- [ ] Support des chaînes intermédiaires
- [ ] Auditing et logging
- [ ] Auditing et logging complet
- [ ] Rate limiting et throttling
- [ ] Support HSM (Hardware Security Module)
---