Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 41 additions & 60 deletions PR_BODY.md
Original file line number Diff line number Diff line change
@@ -1,73 +1,54 @@
## [Backend] Implement comprehensive API documentation with OpenAPI/Swagger
# feat(contracts): add batch credential operations for institutions β€” resolves #8

**Closes #173**
> **Issue:** https://github.com/Epondia/starked-education/issues/8
> **Assignee:** jonathanayubausara-a11y
> **Branch:** `feat/issue-8-batch-credential-operations`
> **Closes:** #8

### Summary
## Summary

This PR implements comprehensive OpenAPI 3.0 specification and Swagger UI for all backend API endpoints, addressing issue #173.
Adds three batch credential operations (`batch_issue`, `batch_revoke`, `batch_renew`) to the Soroban credential registry smart contract, enabling institutions to issue, revoke, and renew up to 100 credentials in a single transaction. Each operation supports **partial failure** β€” individual items that fail validation are skipped with an error recorded in the result, so one problematic credential doesn't block the entire batch.

### Changes Made
Also introduces a configurable `max_batch_size` (default 100) that administrators can adjust, and enhances the `CredentialRegistry` struct with explicit `issued_at` / `expires_at` timestamp fields (replacing `PackedTimestamps`) for clearer expiration management.

#### 1. OpenAPI Specification (`backend/src/config/swagger.js`)
- Created a comprehensive OpenAPI 3.0 specification file documenting **265 API paths**, **94 request/response schemas**, across **30 tagged endpoint groups**
- All major API modules documented with detailed schemas, parameters, and responses:
- Authentication (register, login, profile, role management)
- Health (liveness, readiness, comprehensive health check)
- Users (profile, settings, achievements, stats)
- Content (IPFS upload, retrieve, pin, cache management)
- Courses (version control, comparison, export, statistics)
- Quizzes (CRUD, submission, grading, statistics)
- Enrollments (enroll, progress, waitlist, analytics, certificates)
- Payments (intent, Stellar, refunds, webhooks, exchange rates)
- Search (query, suggestions, voice, recommendations, trending)
- Notifications (list, mark read, preferences)
- Smart Wallet (create, execute, recovery, multisig, session keys)
- Federated Learning (sessions, participants, rounds, models, privacy)
- Swarm Learning (initialize, swarms, agents, tasks, analytics)
- AGI Tutor (sessions, assessments, guidance, recommendations)
- Time-Lock Credentials (issue, release, revoke, schedule, audit)
- VRF (randomness, commit-reveal, beacon, stats)
- Translation (text, batch, subtitles, correction, quality)
- Cross-Protocol Bridge (send, proof, gas cost, stats)
- Admin (dashboard, logs, reports, settings, backup, announcements)
- ACO (learning paths, resources, replanning, swarm, analytics)
- Assignments (CRUD, submissions, grading, bulk, progress)
- RBAC, Gamification, Autonomous Agents, Holographic, Secure Communication
## What changes

#### 2. Authentication Scheme
- JWT Bearer token authentication documented as `BearerAuth` security scheme
- API Key authentication documented as `ApiKeyAuth`
- Applied to all protected endpoints with appropriate security requirements
### Modified
- **`contracts/src/credential_registry.rs`** β€” adds `batch_issue_credentials`, `batch_revoke_credentials`, `batch_renew_credentials`, `get_max_batch_size`, and `set_max_batch_size`. Also adds supporting types: `BatchIssueInput`, `BatchRenewInput`, `BatchResult`, `BatchConfigKey`, `RenewalRecord`, and `CredentialEvent`.
- **`contracts/src/lib.rs`** β€” registers the `credential_registry` module and its test module.

#### 3. Swagger UI Integration (`backend/src/index.js`)
- Swagger UI mounted at `/api-docs` with interactive documentation browser
- Raw OpenAPI spec served as JSON at `/api-docs.json`
- Features: authorization persistence, request duration display, endpoint filtering
### Added
- **`contracts/src/credential_registry_test.rs`** β€” 27 unit tests covering:
- AC 1: Batch issue 50 credentials β€” all succeed
- AC 2: Batch includes one invalid item β€” valid ones still issued, invalid skipped
- AC 3: Batch revoke 30 credentials β€” all marked revoked
- AC 4: Batch renew 20 credentials β€” all expiry dates extended
- AC 5: Exceeding max batch size rejected with clear error
- AC 6: Partial success semantics (per-credential atomicity)
- Authorization checks (unauthorized issuer/revoker/renewer rejected)
- Edge cases (empty batch, zero validity duration, non-existent IDs, already-revoked, recipient-based renewal, batch config)

#### 4. Frontend Type Generation (`frontend/package.json`)
- Added `generate-api-types` script to auto-generate TypeScript types from the OpenAPI spec
- Added `generate-api-types:local` script for offline/cached generation
- Installed `openapi-typescript` dev dependency
## Design decisions

#### 5. Documentation Strategy
- Added comprehensive strategy comment explaining how to keep docs in sync with code
- Centralized spec mirrors actual route structure for maintainability
- **Per-credential atomicity, not whole-batch rollback.** If one credential in a batch fails validation (e.g. zero validity duration, already revoked, not found), it's recorded as a failure in the `BatchResult` and the rest continue processing. This avoids the gas cost of rollback logic and matches real-world institution workflows where partial success is acceptable.
- **Configurable batch ceiling.** `DEFAULT_MAX_BATCH_SIZE = 100` with `set_max_batch_size` (admin-gated) so institutions can tune the limit as gas costs evolve on Stellar/Soroban.
- **Individual events per credential.** Each successful operation emits its own event (`batch_issued`, `batch_revoked`, `batch_renewed`), keeping the event log granular for off-chain indexing.
- **Renewal history tracked.** Every renewal records a `RenewalRecord` (old/new expiry, renewer, timestamp) stored under `RenewalHistory(credential_id)` for auditability.
- **Recipient self-renewal.** `batch_renew_credentials` allows the credential recipient to renew their own credentials, not just the admin. Unauthorized users are rejected per-item.

### Dependencies Added
- `swagger-jsdoc` (^6.3.0) - OpenAPI spec generation
- `swagger-ui-express` (^5.0.1) - Swagger UI serving
- `openapi-typescript` (^7.13.0, frontend devDep) - Type generation
## Validation

### How to Test
- `cargo build --lib` β€” **βœ… passes** with zero new errors (7 pre-existing warnings in unrelated files)
- `cargo test` β€” pre-existing compilation errors in unrelated test files (governance, user_profile, dna_storage, analytics, etc.) prevent a full run; these are tracked separately. The CI config already has `continue-on-error: true` for this step.
- Manual verification: the 8 `*u64` dereference errors that would have caused a CI build failure were fixed in this PR.

1. Start the backend: `cd backend && npm run dev`
2. Visit http://localhost:3001/api-docs to see the interactive Swagger UI
3. Try out endpoints using the "Try it out" feature with JWT authentication
4. Generate frontend types: `cd frontend && npm run generate-api-types`
## Out of scope / Follow-ups

### Checklist
- [x] All API endpoints documented with request/response schemas
- [x] Authentication scheme (JWT Bearer) documented
- [x] Swagger UI available at `/api-docs`
- [x] Frontend type generation scripts added
- [x] Documentation strategy documented for code sync
1. **Fix pre-existing test compilation errors** across `governance_test.rs`, `user_profile_test.rs`, `dna_storage_test.rs`, etc. (~49 errors from `#![no_std]` macro/import issues). Tracked separately.
2. **Gas benchmarking** β€” measure batch operation gas costs under realistic loads and tune `max_batch_size`.
3. **Indexed storage for `get_credentials_expiring_soon`** β€” currently O(n) linear scan; add a time-indexed data structure for production use.
4. **Event indexing integration** β€” wire batch events into the backend event logger for dashboards.

---

πŸ€– Generated with assistance from Codebuff; reviewed and signed off by the human collaborator.
Loading
Loading